← 中文资源

简体中文版本

用 ZoneInfo 的 fold 区分夏令时回拨时刻

在夏令时回拨重叠时段用 datetime 的 fold=0 与 fold=1 区分首次与二次经过同一墙钟时刻,并借 UTC 往返检测春季跳空不存在的本地时间。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

fold=0: 2026-11-01T01:30:00-04:00 -> UTC: 2026-11-01T05:30:00+00:00
fold=1: 2026-11-01T01:30:00-05:00 -> UTC: 2026-11-01T06:30:00+00:00
gap hours: 1
2026-03-08T01:45:00 exists: True
2026-03-08T02:30:00 exists: False

实现说明

用 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))