Sub topic 8
Ambiguous and nonexistent times around DST
This chapter assumes you can already use tz_localize and know the difference between naive and aware timestamps. It covers what happens when a naive local time falls on a daylight saving time (DST) change.
Why some local times break
A naive timestamp has no zone, so pandas must look up the UTC offset for that wall-clock time in the IANA database. Twice a year in a DST zone, that lookup does not give exactly one answer.
- Fall back: clocks move back an hour. In New York on 2024-11-03, the hour from 01:00 to 02:00 happens twice. A time such as 01:30 is ambiguous.
- Spring forward: clocks jump ahead an hour. On 2024-03-10, 02:00 becomes 03:00. A time such as 02:30 is nonexistent.
By default pandas refuses to guess. It raises an error instead of silently choosing one offset.
Ambiguous times
The default is ambiguous="raise", which raises AmbiguousTimeError. You can choose another resolution:
| Value | Effect |
|---|---|
| `"raise"` | Raise `AmbiguousTimeError` (default) |
| `"NaT"` | Replace ambiguous times with `NaT` |
| boolean array | `True` means the first occurrence (DST, -04:00). `False` means the second (standard time, -05:00). |
| `"infer"` | Work out the order from the sequence. The values must be sorted and include both occurrences. |
import numpy as np
import pandas as pd
tz = "America/New_York"
# 2024-11-03 01:30 happens twice when clocks fall back
ambiguous = pd.DatetimeIndex(["2024-11-03 01:30"])
try:
ambiguous.tz_localize(tz)
except Exception as e:
print(type(e).__name__) # AmbiguousTimeError
print(ambiguous.tz_localize(tz, ambiguous=np.array([True]))) # first occurrence, -04:00
print(ambiguous.tz_localize(tz, ambiguous="NaT")) # NaTThe boolean array must have one entry per timestamp. That is useful when another column tells you which occurrence each row is, for example a logged "is DST" flag.
"infer" suits a regular log that runs straight through the transition:
import pandas as pd
idx = pd.DatetimeIndex([
"2024-11-03 00:30",
"2024-11-03 01:30",
"2024-11-03 01:30",
"2024-11-03 02:30",
])
print(idx.tz_localize("America/New_York", ambiguous="infer"))
# 00:30-04:00, 01:30-04:00, 01:30-05:00, 02:30-05:00"infer" fails if the data is unsorted or if only one of the two repeated times is present, because it has nothing to compare against.
Nonexistent times
The default is nonexistent="raise", which raises NonExistentTimeError. The other options:
"shift_forward"moves the time to the first valid instant after the gap."shift_backward"moves it to the last valid instant before the gap."NaT"replaces it withNaT.- A
pd.Timedeltashifts the time by that amount.
import pandas as pd
tz = "America/New_York"
# 2024-03-10 02:30 does not exist when clocks spring forward
missing = pd.DatetimeIndex(["2024-03-10 02:30"])
print(missing.tz_localize(tz, nonexistent="shift_forward")) # 2024-03-10 03:00:00-04:00
print(missing.tz_localize(tz, nonexistent="shift_backward")) # 2024-03-10 01:59:59.999999999-05:00Note that shift_forward gives 03:00, not 03:30. It snaps to the edge of the gap and does not preserve the minutes.
Applying this to a Series
The same arguments work on a Series through .dt.tz_localize. A value that fails raises an error for the whole call, so choose your policy before localizing a large column.
import pandas as pd
s = pd.Series(pd.to_datetime(["2024-03-10 02:30", "2024-03-10 09:00"]))
fixed = s.dt.tz_localize("America/New_York", nonexistent="NaT")
print(fixed) # first value is NaT, second is 09:00-04:00
print(fixed.isna().sum()) # 1Common errors
- Localizing data that is already UTC. If the source stores UTC, localize to
"UTC"first and then usetz_convert. Local-time ambiguity only exists in naive local data. - Using
"NaT"and not checking. Dropped values spread silently. Count them withisna()afterward. - Assuming
"infer"always works. It needs sorted, complete data. - Applying
tz_localizeto an aware timestamp. This raises an error. Usetz_convertto change zone.
Exercise
A naive timestamp "2024-03-10 02:15" is localized to "America/New_York" with the default arguments. What happens, and which argument value turns the result into 03:00 local time?
Show answer
It raises NonExistentTimeError, because clocks jump from 02:00 to 03:00 and 02:15 never occurs. Passing nonexistent="shift_forward" returns 2024-03-10 03:00:00-04:00.