Save timestamps in UTC but display them using the reader’s timezone.
How It Works
Aware UTC datetimes are convenient for logging and data exchange because they identify a clear instant. astimezone() converts that same instant to an IANA geographic timezone with the appropriate offset for that date. Preserve the offset or timezone information in storage and APIs.
The timezone database may be supplied by the operating system or tzdata package.
Step-by-Step Example
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
stored = datetime(2026, 1, 15, 10, 0, tzinfo=timezone.utc)
local = stored.astimezone(ZoneInfo("Europe/Paris"))
print(stored.isoformat())
print(local.isoformat())
print(stored.timestamp() == local.timestamp())
Understanding the Example
- The expression 'datetime(2026, 1, 15, 10, 0, tzinfo=timezone.utc)' supplies the value stored as 'stored'. This value is then used or checked by the later statements.
- The expression 'stored.astimezone(ZoneInfo("Europe/Paris"))' supplies the value stored as 'local'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
2026-01-15T10:00:00+00:00
2026-01-15T11:00:00+01:00
True
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
Convert the same UTC instant to two named zones and verify their timestamps match.
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
- Calling replace(tzinfo=...) on UTC clock values instead of converting the instant with astimezone().
- Storing unlabeled local clock readings that cannot be reliably interpreted later.
Key Takeaways
- Save timestamps in UTC but display them using the reader’s timezone.
- Aware UTC datetimes are convenient for logging and data exchange because they identify a clear instant.
- The timezone database may be supplied by the operating system or tzdata package.