实现说明
用 ZoneInfo 的 fold 区分夏令时回拨时刻以函数 is_valid_local_wall_time为骨架。
for candidate in (datetime(2026, 3, 8, 1, 45), datetime(2026, 3, 8, 2, 30)) 是唯一的迭代点——其余代码顺序执行一遍。
使用要点
- 依赖列表保持空白,依靠语言自带运行时即可全部覆盖。
- 跑完文件,输出里会留下标记——
fold=0:、fold=1:、gap hours:。 - 把
is_valid_local_wall_time当作 API:导入它,其余代码可以忽略。
常见问题
在一个没有任何依赖声明的空项目里能跑吗?
可以——空项目原样能跑,因为什么都不用声明。 全部导入都来自标准库:datetime、zoneinfo。 文件在加载时定义 is_valid_local_wall_time。
主要签名是 def is_valid_local_wall_time(naive_dt: datetime, tz: ZoneInfo) -> bool
核心语句
def is_valid_local_wall_time(naive_dt: datetime, tz: ZoneInfo) -> bool:
aware = naive_dt.replace(tzinfo=tz)
roundtrip = aware.astimezone(timezone.utc).astimezone(tz)
return roundtrip.replace(tzinfo=None) == naive_dt
代码示例
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
ny = ZoneInfo("America/New_York")
# Fall-back overlap on 2026-11-01: 01:30 occurs twice (EDT -04:00 then EST -05:00)
first_pass = datetime(2026, 11, 1, 1, 30, tzinfo=ny, fold=0)
second_pass = datetime(2026, 11, 1, 1, 30, tzinfo=ny, fold=1)
print("fold=0:", first_pass.isoformat(), "-> UTC:", first_pass.astimezone(timezone.utc).isoformat())
print("fold=1:", second_pass.isoformat(), "-> UTC:", second_pass.astimezone(timezone.utc).isoformat())
print("gap hours:", (second_pass.astimezone(timezone.utc) - first_pass.astimezone(timezone.utc)).seconds // 3600)
# Spring-forward gap on 2026-03-08: 02:30 never exists on local clocks
def is_valid_local_wall_time(naive_dt: datetime, tz: ZoneInfo) -> bool:
aware = naive_dt.replace(tzinfo=tz)
roundtrip = aware.astimezone(timezone.utc).astimezone(tz)
return roundtrip.replace(tzinfo=None) == naive_dt
for candidate in (datetime(2026, 3, 8, 1, 45), datetime(2026, 3, 8, 2, 30)):
print(candidate.isoformat(), "exists:", is_valid_local_wall_time(candidate, ny))