Zoneinfo Arithmetic Crosses DST

Add timedelta to aware datetimes across a DST switch: wall-clock arithmetic keeps 7 hours but the UTC span changes — the booking-code contract.

PythonData Integrity

Code

pythonsnippet
20 lines
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

UTC = timezone.utc
# 2026-03-08 美东切夏令时:起飞在 EST(-5),落地在 EDT(-4)
flight = datetime(2026, 3, 7, 23, 30, tzinfo=ZoneInfo("America/New_York"))

# aware datetime 的 timedelta 算术按墙上时间推进
landing = flight + timedelta(hours=7)
print("depart:", flight.isoformat())
print("land  :", landing.isoformat())

# 墙钟走了 7 小时,UTC 差却是 6 小时 —— 春令时时钟前拨,UTC 跨度反而更短;预订系统必须按这个口径算时长
span = landing.astimezone(UTC) - flight.astimezone(UTC)
print("utc span:", span / timedelta(hours=1), "h")

# 同一时刻在不同时区的呈现:换算不改变时间点本身
moment = datetime(2026, 1, 15, 12, 0, tzinfo=UTC)
for zone in ("Asia/Shanghai", "Europe/Berlin", "America/Los_Angeles"):
    print(zone.rjust(20), moment.astimezone(ZoneInfo(zone)).strftime("%Y-%m-%d %H:%M"))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

depart: 2026-03-07T23:30:00-05:00
land  : 2026-03-08T06:30:00-04:00
utc span: 6.0 h
       Asia/Shanghai 2026-01-15 20:00
       Europe/Berlin 2026-01-15 13:00
 America/Los_Angeles 2026-01-15 04:00

How it works

for zone in ("Asia/Shanghai", "Europe/Berlin", "America/Los_Angeles") is the loop that carries the per-item work. From zoneinfo it pulls datetime, timedelta, timezone, ZoneInfo — the imports name exactly which library surface the snippet touches.

The file’s state is a handful of top-level bindings: flight, landing, span, moment.

What to watch for

  • External dependency: zoneinfo — install it before running the snippet.

Using it

Running the file prints labeled results such as depart:, land :, utc span: — each operation’s effect is visible in the output.

Key statements

for zone in ("Asia/Shanghai", "Europe/Berlin", "America/Los_Angeles"):
    print(zone.rjust(20), moment.astimezone(ZoneInfo(zone)).strftime("%Y-%m-%d %H:%M"))

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Every import resolves inside the standard library — `datetime`, `zoneinfo`. Its state lives in module-level bindings: `flight`, `landing`, `span`.