Zoneinfo Converts Datetimes Across Timezones
Store datetimes in UTC and convert with ZoneInfo: one meeting renders as different wall clocks, and New York moves between UTC-5 and UTC-4 with DST.
Code
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
# 存储层固定用 UTC 的 aware datetime
meeting = datetime(2026, 7, 1, 15, 0, tzinfo=timezone.utc)
print("utc:", meeting.isoformat())
# 同一时刻在不同时区(timezone)的墙钟时间
print("shanghai:", meeting.astimezone(ZoneInfo("Asia/Shanghai")).isoformat())
print("new york:", meeting.astimezone(ZoneInfo("America/New_York")).isoformat())
# 夏令时对照:纽约 1 月是 UTC-5,7 月是 UTC-4
winter = datetime(2026, 1, 15, 12, 0, tzinfo=timezone.utc)
print("ny winter:", winter.astimezone(ZoneInfo("America/New_York")).isoformat())
# naive datetime 不能与 aware 比较:先挂上时区
naive = datetime(2026, 7, 1, 15, 0)
aware = naive.replace(tzinfo=ZoneInfo("Asia/Shanghai"))
print("shanghai offset:", aware.utcoffset())Output
Captured from a sandboxed run of this snippet in the build pipeline.
utc: 2026-07-01T15:00:00+00:00
shanghai: 2026-07-01T23:00:00+08:00
new york: 2026-07-01T11:00:00-04:00
ny winter: 2026-01-15T07:00:00-05:00
shanghai offset: 8:00:00How the snippet works
Reach for zoneinfo and what you get is datetime, timezone, ZoneInfo — that is the whole API contact area.
The demo data lives in module-level bindings: meeting, winter, naive, aware.
What to watch for
- Dependency check:
zoneinfo— not built-in, must be present in the project.
Applying it
Output lines are prefixed (utc:, shanghai:, new york:), making each step’s effect easy to spot.
Interactive Tools for This Topic
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Timezone Offset FinderLook up the UTC offset, abbreviation, and local time for any IANA time zone at a given instant, and see whether the zone observes daylight saving.
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `datetime`, `zoneinfo`. Its state lives in module-level bindings: `meeting`, `winter`, `naive`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.