Junior — Middle
How to handle time zones and daylight saving time in Python?
sobes.tech AI
Answer from AI
For working with time zones and time conversion in Python, it is recommended to use the datetime module along with the pytz library or the built-in zoneinfo module in Python 3.9+.
Example using pytz:
from datetime import datetime
import pytz
# Create a naive datetime object (without timezone)
naive_dt = datetime(2024, 4, 27, 15, 30)
# Define the timezone
moscow_tz = pytz.timezone('Europe/Moscow')
# Localize the time (attach timezone)
aware_dt = moscow_tz.localize(naive_dt)
# Convert to another timezone
new_york_tz = pytz.timezone('America/New_York')
ny_time = aware_dt.astimezone(new_york_tz)
print(aware_dt) # 2024-04-27 15:30:00+03:00
print(ny_time) # 2024-04-27 08:30:00-04:00
If using Python 3.9 or higher, you can use zoneinfo:
from datetime import datetime
from zoneinfo import ZoneInfo
naive_dt = datetime(2024, 4, 27, 15, 30)
moscow_dt = naive_dt.replace(tzinfo=ZoneInfo('Europe/Moscow'))
ny_dt = moscow_dt.astimezone(ZoneInfo('America/New_York'))
print(moscow_dt)
print(ny_dt)
It is always important to work with "aware" datetime objects (with timezone information) to avoid errors in time conversion and calculations.