Use the IANA timezone database with zoneinfo.ZoneInfo.
How It Works
ZoneInfo("Area/City") applies geographic timezone rules, including daylight-saving offsets for supported dates. On platforms without installed timezone data, install the tzdata package or provide system timezone information.
Step-by-Step Example
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
utc_time = datetime(2026, 1, 15, 12, tzinfo=timezone.utc)
local_time = utc_time.astimezone(ZoneInfo('America/New_York'))
print(local_time.hour)
print(local_time.tzinfo.key)
Understanding the Example
- The expression 'datetime(2026, 1, 15, 12, tzinfo=timezone.utc)' supplies the value stored as 'utc_time'. This value is then used or checked by the later statements.
- The expression "utc_time.astimezone(ZoneInfo('America/New_York'))" supplies the value stored as 'local_time'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
7
America/New_York
Where This Fits in a Real Program
For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.
Practice: Try It Yourself
The available timezone data comes from the system or the tzdata package.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Assuming a city uses the same fixed UTC offset throughout the year.
- Compare a January and July UTC timestamp for one IANA timezone.
Key Takeaways
- Use the IANA timezone database with zoneinfo.ZoneInfo.
- ZoneInfo("Area/City") applies geographic timezone rules, including daylight-saving offsets for supported dates.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.