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.

PythonData Integrity

Code

pythonsnippet
19 lines
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:00

How 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

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`.