Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save inirudebwoy/71b8bd4e7fa0425c9940d75fba0f7cd5 to your computer and use it in GitHub Desktop.
Save inirudebwoy/71b8bd4e7fa0425c9940d75fba0f7cd5 to your computer and use it in GitHub Desktop.
This code snippet defines a function that takes a datetime and a timezone name as input and returns the datetime converted to the specified timezone. It assumes that naive datetimes are in UTC.

Convert time to specified timezone using pytz

Preview:
def get_local_time(dt: datetime, timezone_name: str) -> datetime:
    """Convert given time to timezone. Naive datetimes are assumed to be in UTC"""
    tz = pytz.timezone(timezone_name)
    return to_zoned_utc(dt).astimezone(tz)
Associated Context
Type Code Snippet ( .py )
Associated Tags utc datetime manipulation datetime Object-Oriented Programming pytz Library pytz Date Manipulation naive datetime Type Checking Data Types astimezone method Local Time Conversion Python Function DateTime Formatting timezone date-conversion pytz library Framework: pytz timezone name zoned UTC UTC TimeZone datetime conversion time conversion timezone conversion django
💡 Smart Description This function converts a given time to the timezone and returns it in UTC. It also allows us to use Naive datetimes as an absolute date format for testing purposes.
This code snippet defines a function that takes a datetime and a timezone name as input and returns the datetime converted to the specified timezone. It assumes that naive datetimes are in UTC.
🔎 Suggested Searches function to convert time to timezone
How to get local time from datetime using Python
function to convert given time to a zone
Converting date to UTC in python
pytz
Convert time to specific timezone in Python
Python function to convert time to different timezone
How to convert UTC time to local time in Python
Python code to convert datetime to specific timezone
Using pytz library to convert time to different timezone in Python
Related Links https://www.w3schools.com/python/python_datetime.asp
https://realpython.com/python-datetime/
https://www.programiz.com/python-programming/datetime
https://www.programiz.com/python-programming/datetime/current-datetime
https://docs.python.org/3/library/datetime.html
https://www.guru99.com/date-time-and-datetime-classes-in-python.html
https://www.programiz.com/python-programming/datetime/strftime
https://www.tutorialspoint.com/python/python_date_time.htm
https://pytz.sourceforge.net/
Related People No Related People
Sensitive Information No Sensitive Information Detected
Shareable Link https://user-0d37fcb9-88ce-4ecb-9ccd-3ce910f522bf-tefd7kihka-uw.a.run.app/?p=bb0b4696ea
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment