Turn UTC timestamps into local display values without changing the instant.
How It Works
Unix timestamps identify seconds relative to 1970-01-01 UTC. Parse them with datetime.fromtimestamp(value, timezone.utc) and then convert to the target ZoneInfo. The local date may differ from the UTC date.
Step-by-Step Example
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
utc_datetime = datetime.fromtimestamp(0, timezone.utc)
new_york_time = utc_datetime.astimezone(ZoneInfo('America/New_York'))
print(utc_datetime.hour)
print(new_york_time.year)
Understanding the Example
- The expression 'datetime.fromtimestamp(0, timezone.utc)' supplies the value stored as 'utc_datetime'. This value is then used or checked by the later statements.
- The expression "utc_datetime.astimezone(ZoneInfo('America/New_York'))" supplies the value stored as 'new_york_time'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
0
1969
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
Display formatting belongs after timezone conversion, not before.
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
- Interpreting a Unix millisecond value as seconds or using a fixed offset year-round.
- Convert a saved UTC Unix timestamp to two cities with different zones.
Key Takeaways
- Turn UTC timestamps into local display values without changing the instant.
- Unix timestamps identify seconds relative to 1970-01-01 UTC.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.