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
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
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
Snippet 4: Convert Between Time Zones
Snippet 5: Make a Naive Datetime Time Zone-Aware
Snippet 6: Handling Daylight Saving Time (DST)
Snippet 7: Calculate Time Difference Between Two Time Zones
Snippet 8: Convert String to Time Zone-Aware Datetime
Snippet 9: Get UTC Offset of a Time Zone
Snippet 10: Find Current Time in Multiple Time Zones
Last updated