Sub topic 8
Ambiguous and nonexistent times around DST
This chapter assumes you can already attach a zone with tz_localize and change it with tz_convert. It covers the two cases where tz_localize cannot pick a single instant for a wall-clock time. Both happen when daylight saving time (DST) shifts the clocks.
Why some wall-clock times break localization
A naive timestamp such as 2024-11-03 01:30 gives only a date and a clock reading. tz_localize has to turn that reading into one instant on the UTC timeline. For most readings that works. Twice a year in a DST zone it does not:
- Clocks fall back (autumn). The clock repeats an hour. A reading in that hour matches two instants, so it is ambiguous.
- Clocks spring forward (spring). The clock skips an hour. A reading in that hour matches no instant, so it is nonexistent.
In America/New_York in 2024, the changes happened on these dates:
| Date | Local change | UTC moment | Result for naive readings |
|---|---|---|---|
| 2024-03-10 | 02:00 EST jumps to 03:00 EDT | 07:00 UTC | 02:00 to 02:59 never happens |
| 2024-11-03 | 02:00 EDT falls back to 01:00 EST | 06:00 UTC | 01:00 to 01:59 happens twice |
By default, pandas refuses to guess in either case and raises an error. That is usually correct. A silent guess would shift your data by an hour without telling you.
Ambiguous times
Here is the default behavior on the repeated hour:
import numpy as np
import pandas as pd
tz = "America/New_York"
ambiguous = pd.DatetimeIndex(["2024-11-03 01:30"])
try:
ambiguous.tz_localize(tz)
except Exception as e:
print(type(e).__name__) # AmbiguousTimeErrorThe ambiguous argument tells pandas how to resolve the reading. It accepts four kinds of values:
| Value | Meaning |
|---|---|
| `"raise"` (default) | Raise `AmbiguousTimeError` |
| `True` / `False`, or a boolean array | `True` means the DST (first) occurrence. `False` means the standard-time (second) occurrence. |
| `"NaT"` | Replace ambiguous readings with `NaT` |
| `"infer"` | Work out the occurrence from the order of the data (DatetimeIndex and Series only) |
A boolean is a statement about DST. True means "this reading is in daylight time", which in New York is the first pass at -04:00. False means the second pass at -05:00.
import pandas as pd
tz = "America/New_York"
reading = pd.Timestamp("2024-11-03 01:30")
first = reading.tz_localize(tz, ambiguous=True)
second = reading.tz_localize(tz, ambiguous=False)
print(first) # 2024-11-03 01:30:00-04:00
print(second) # 2024-11-03 01:30:00-05:00
print(second - first) # 0 days 01:00:00The two results have the same wall-clock reading but are one hour apart in real time.
Passing an array of flags
For a whole column, pass one flag per row. This fits when your source system records whether each row was in DST. The array must have the same length as the data, and the flags only matter for rows that are actually ambiguous.
import numpy as np
import pandas as pd
tz = "America/New_York"
idx = pd.DatetimeIndex(["2024-11-03 01:30", "2024-11-03 01:30"])
fixed = idx.tz_localize(tz, ambiguous=np.array([True, False]))
print(fixed) # first row at -04:00, second row at -05:00Letting pandas infer the order
Log files often contain the repeated hour as two runs of rows. If the rows are in chronological order, ambiguous="infer" assigns the first run to DST and the second to standard time.
import pandas as pd
tz = "America/New_York"
log = pd.Series(pd.to_datetime([
"2024-11-03 00:30",
"2024-11-03 01:30",
"2024-11-03 01:30",
"2024-11-03 02:30",
]))
resolved = log.dt.tz_localize(tz, ambiguous="infer")
print(resolved)
# 00:30-04:00, 01:30-04:00, 01:30-05:00, 02:30-05:00Treat "infer" with care:
- The data must be sorted in time order. Out-of-order rows give wrong answers or an error.
- Each ambiguous reading must appear the right number of times. A log that dropped the second
01:30row confuses the inference. - It cannot work on a single
Timestamp, because there is no surrounding order to read.
Dropping ambiguous rows with NaT
If a few repeated-hour rows are not worth rescuing, mark them as missing and filter afterward:
import pandas as pd
tz = "America/New_York"
s = pd.Series(pd.to_datetime(["2024-11-03 00:30", "2024-11-03 01:30"]))
out = s.dt.tz_localize(tz, ambiguous="NaT")
print(out.isna().tolist()) # [False, True]
print(out.dropna())Check how many rows you lose before dropping them. Silent deletion of an hour of data is a data quality bug of its own.
Nonexistent times
The spring-forward gap works the same way, using the nonexistent argument. A reading such as 2024-03-10 02:30 never appeared on any New York clock.
import pandas as pd
tz = "America/New_York"
missing = pd.DatetimeIndex(["2024-03-10 02:30"])
try:
missing.tz_localize(tz)
except Exception as e:
print(type(e).__name__) # NonExistentTimeErrorThe options are:
| Value | Result for `02:30` on 2024-03-10 |
|---|---|
| `"raise"` (default) | Raises `NonExistentTimeError` |
| `"shift_forward"` | `03:00:00-04:00`, the first valid instant after the gap |
| `"shift_backward"` | `01:59:59.999999999-05:00`, the last valid instant before the gap |
| `"NaT"` | `NaT` |
| a `Timedelta` | The reading shifted by that amount, so `1h` gives `03:30:00-04:00` |
import pandas as pd
tz = "America/New_York"
gap = pd.Timestamp("2024-03-10 02:30")
print(gap.tz_localize(tz, nonexistent="shift_forward")) # 2024-03-10 03:00:00-04:00
print(gap.tz_localize(tz, nonexistent="shift_backward")) # 2024-03-10 01:59:59.999999999-05:00
print(gap.tz_localize(tz, nonexistent=pd.Timedelta("1h"))) # 2024-03-10 03:30:00-04:00
print(gap.tz_localize(tz, nonexistent="NaT")) # NaTEach option fits a different situation:
- Use
shift_forwardfor a scheduled event such as "run at 02:30". Most schedulers run the job as soon as the gap ends. - Use
shift_backwardwhen you want a reading to stay inside the interval that ended at the gap, for example when assigning rows to a closed hour. - Use a
Timedeltashift when you want to preserve the offset into the hour (02:30becomes03:30). - Use
NaTor"raise"when a reading in the gap signals corrupt data. Nothing legitimate was recorded by a New York clock at 02:30 that morning.
You can pass ambiguous and nonexistent in the same call, which is common for a real column that spans both transitions:
import pandas as pd
tz = "America/New_York"
s = pd.Series(pd.to_datetime([
"2024-03-10 01:30",
"2024-03-10 02:30",
"2024-11-03 01:30",
]))
out = s.dt.tz_localize(tz, ambiguous="NaT", nonexistent="shift_forward")
print(out)
# 01:30-05:00, 03:00-04:00, NaTChoosing a strategy
The first question matters most. Naive local times lose information at the moment they are written. If you control the source, store UTC or timestamps with offsets, and you never face an ambiguous reading. The options above are repairs for data that has already lost that information.
Edge cases to know
- Only affected rows matter. Errors fire only if some row falls in a repeated or skipped hour. A pipeline can run for months and fail on the first Sunday of November. Test your code against the transition dates.
tz_convertnever raises these errors. Converting from an aware timestamp is always exact, because every instant has exactly one local reading. The errors arise only when you go from naive to aware.- Zones differ. Not every zone has DST, and the transition dates differ by zone and by year.
UTCand fixed-offset zones never have ambiguous or nonexistent readings. Southern Hemisphere zones fall back in autumn, which is April. - Other methods accept the same arguments.
Timestamp.floor,ceilandroundtakeambiguousandnonexistenttoo. Rounding an aware timestamp down to a day or an hour can land in a repeated or skipped hour, so they need the same decision. - Partial transitions exist. Some zones shift by 30 minutes, such as
Australia/Lord_Howe. The repeated or skipped span is then 30 minutes long, and the same arguments apply.
Exercises
Exercise
A sensor logs naive local times in America/New_York and includes the repeated hour on 2024-11-03 as two rows that both read 01:30. The rows are in chronological order. Which tz_localize argument assigns the first row to -04:00 and the second to -05:00 without a flag column, and what must be true of the data?
Show answer
Use ambiguous="infer", for example s.dt.tz_localize("America/New_York", ambiguous="infer"). The rows must be sorted in time order and the repeated readings must both be present, because pandas infers the occurrence from the order of the rows.
Exercise
You localize the naive reading 2024-03-10 02:30 in America/New_York with nonexistent="shift_backward". What do you get, and how does it differ from nonexistent="shift_forward"?
Show answer
shift_backward gives 2024-03-10 01:59:59.999999999-05:00, the last instant before the gap. shift_forward gives 2024-03-10 03:00:00-04:00, the first instant after the gap. The two results are one nanosecond apart in real time, because both sit at the edges of the same transition.
Exercise
A teammate says that ts_utc.tz_convert("America/New_York") raises AmbiguousTimeError for an instant that falls in the repeated hour. Are they right? Explain.
Show answer
No. Every instant in UTC maps to exactly one local reading, so tz_convert always succeeds. For the repeated hour it produces 01:30-04:00 for the first pass and 01:30-05:00 for the second. The error occurs only in tz_localize, where a naive reading must be turned into an instant.