154. Handling Time Zones with pytz

Here are 10 Python snippets demonstrating how to handle time zones with the pytz library. Each snippet is separated by a delimiter.


Snippet 1: Convert UTC Time to Local Time

Copy

from datetime import datetime
import pytz

utc_time = datetime.utcnow()
utc_zone = pytz.utc
local_zone = pytz.timezone('Asia/Kolkata')

utc_time_aware = utc_zone.localize(utc_time)
local_time = utc_time_aware.astimezone(local_zone)

print("UTC Time:", utc_time)
print("Local Time:", local_time)

Snippet 2: Get Current Time in a Specific Time Zone

Copy

from datetime import datetime
import pytz

tz = pytz.timezone('America/New_York')
current_time = datetime.now(tz)

print("Current Time in New York:", current_time)

Snippet 3: List All Available Time Zones

Copy


Snippet 4: Convert Between Time Zones

Copy


Snippet 5: Make a Naive Datetime Time Zone-Aware

Copy


Snippet 6: Handling Daylight Saving Time (DST)

Copy


Snippet 7: Calculate Time Difference Between Two Time Zones

Copy


Snippet 8: Convert String to Time Zone-Aware Datetime

Copy


Snippet 9: Get UTC Offset of a Time Zone

Copy


Snippet 10: Find Current Time in Multiple Time Zones

Copy


Last updated