skip to content

In pandas 3.0, tz_localize on a naive event log fails around a daylight-saving change in Europe/Berlin. What went wrong, and how do the ambiguous and nonexistent arguments fix it?

level: seniorimportance: should knowfreq 35%

answer

  1. an hour that happens twice
  2. an hour that never happens
  3. the default is to raise
  4. order can reveal the first pass
  5. pytz errors no longer surface

basics

~20 s

At the autumn change local 02:00-02:59 happens twice, and in spring it never happens, so tz_localize raises ValueError by default. ambiguous ('infer', a boolean array or 'NaT') and nonexistent ('shift_forward', 'shift_backward', a Timedelta or 'NaT') choose the answer.

solid answer

~40 s

Naive local readings cannot always map to one instant. On the autumn night in Berlin, 02:30 occurs at +02:00 and again at +01:00, so `tz_localize` raises `ValueError` ("Cannot infer dst time"); `ambiguous="infer"` uses the recorded order of the log to tell the passes apart, a boolean array marks True for summer time, and `"NaT"` gives up on those rows. On the spring night, 02:30 does not exist, so it raises a nonexistent-time `ValueError`; `nonexistent="shift_forward"` moves it to 03:00, `"shift_backward"` to the last instant before the gap, a `Timedelta` shifts by that amount, and `"NaT"` drops it. In pandas 3.0 these are plain `ValueError`s, not pytz exceptions, because zoneinfo is the default.

code

python · 20 lines
python
import numpy as np
import pandas as pd

fall = pd.Series(pd.to_datetime([
    "2025-10-26 01:30", "2025-10-26 02:30", "2025-10-26 02:30", "2025-10-26 03:00",
]))
print(fall.dt.tz_localize("Europe/Berlin", ambiguous="infer"))

single = pd.Series(pd.to_datetime(["2025-10-26 02:30"]))
print(single.dt.tz_localize("Europe/Berlin", ambiguous=np.array([False])))

spring = pd.Series(pd.to_datetime(["2025-03-30 01:30", "2025-03-30 02:30"]))
try:
    spring.dt.tz_localize("Europe/Berlin")
except ValueError as err:
    print(err)
print(spring.dt.tz_localize("Europe/Berlin", nonexistent="shift_forward"))

ts = pd.Timestamp("2025-03-29 09:00", tz="Europe/Berlin")
print(ts + pd.offsets.Day(1), ts + pd.Timedelta(days=1))

go deeper

for a junior

Know that a local clock repeats one hour in autumn and skips one in spring, and that tz_localize raises on those readings unless told what to do.

for a middle

Explain each value of ambiguous and nonexistent, especially how infer uses row order and what True means in the boolean array.

for a senior

Choose the repair from how the source clock behaved, count the rows it touched, and update handlers for pandas 3.0's ValueError and calendar-day Day.

for a principal

Push for UTC or offset-carrying data at the source so no pipeline has to guess an hour twice a year.

## Why a naive log breaks at daylight saving A **naive** timestamp such as `2025-10-26 02:30` is a wall-clock reading with no zone. **`.dt.tz_localize("Europe/Berlin")`** must decide which instant that reading meant. For almost every reading there is exactly one answer, but twice a year there is not: - **Fall back (autumn):** clocks go from 03:00 summer time back to 02:00 winter time, so every reading from 02:00 to 02:59 happens **twice**, first at `+02:00` and then at `+01:00`. These times are **ambiguous**. - **Spring forward:** clocks jump from 02:00 to 03:00, so readings from 02:00 to 02:59 **never happen**. These times are **nonexistent**. By default both arguments are `"raise"`, so a single such row makes the whole call fail. In **pandas 3.0** the failure is a plain **`ValueError`**, for example `Cannot infer dst time from 2025-10-26 02:30:00, try using the 'ambiguous' argument` or `2025-03-30 02:30:00 is a nonexistent time due to daylight savings time`. In 2.x, with pytz as the default zone library, pandas raised pytz's own exception classes; any handler written to catch those must now catch `ValueError`. ## The ambiguous argument | value | result for a repeated reading | |---|---| | `"raise"` (default) | `ValueError` | | `"infer"` | decides from the order of the data | | boolean array | `True` = summer time (first pass), `False` = winter time (second pass) | | `"NaT"` | the reading becomes `NaT` | **`"infer"`** works when the log is in recorded order and the repeated hour actually appears twice: pandas sees the clock go backwards and assigns the first run to `+02:00` and the second to `+01:00`. It fails with `Cannot infer dst time ... as there are no repeated times` when only one pass is present, and it usually fails on a log that was sorted by the naive clock after the fact, because sorting interleaves the two passes (for example `There are 2 dst switches when there should only be 1`). A **boolean array** is the precise option when the source gives a hint, for example a separate is-summer-time flag or a sequence number. **`"NaT"`** is honest but lossy; note that it blanks every ambiguous row, both passes. ## The nonexistent argument | value | result for a skipped reading | |---|---| | `"raise"` (default) | `ValueError` | | `"shift_forward"` | the first real instant after the gap (03:00) | | `"shift_backward"` | the last real instant before the gap | | a `Timedelta`, e.g. `pd.Timedelta("1h")` | the reading moved by that amount | | `"NaT"` | the reading becomes `NaT` | `"shift_backward"` lands just before 03:00, at the column's smallest unit: `01:59:59.999999` for a microsecond column, the default for parsed strings in pandas 3.0. A device clock that did not change yet usually means `pd.Timedelta("1h")` is the right repair. ## A related 3.0 change: what "one day later" means In **pandas 3.0, `pd.offsets.Day` is a calendar day**: adding `pd.offsets.Day(1)` to 09:00 the day before spring forward gives 09:00 the next day, 23 hours later. `pd.Timedelta(days=1)` is still exactly 24 hours and gives 10:00. In 2.x, `Day` was a fixed 24 hours. Consequences: 1. `pd.date_range(..., freq="D", tz="Europe/Berlin")` keeps the same local time each day across the change. 2. `Timedelta` no longer accepts a `Day` object as input. 3. Adding a `Day` that lands on an ambiguous or nonexistent local time raises, so the same arguments may be needed downstream. ## Avoiding the problem upstream The arguments are repairs. A better fix is to stop receiving naive local time: - Ask the source for UTC, epoch numbers or strings with an offset, and parse them with `utc=True`. - If only local readings exist, keep a sequence number or a DST flag so the ambiguous hour can be decided with a boolean array rather than guessed. - Count the rows each repair touched (`NaT` rows, shifted rows) and record the choice next to the pipeline. Note that `tz_convert` never meets these problems: converting an aware instant to Berlin time is always well defined. The trouble belongs only to the localize step. ## Interview checklist - Name both cases, which season each belongs to, and the default `"raise"`. - Explain how `"infer"` works and when it cannot. - Pick a `nonexistent` repair and justify it from how the device clock behaved. - Mention that pandas 3.0 raises `ValueError` and treats `Day` as a calendar day.

  • In pandas, why can ambiguous='infer' fail on a log that was sorted by its naive timestamps?
    infer looks for the point where the local clock goes backwards, so it needs the rows in recorded order. Sorting by the naive clock interleaves the two passes of the repeated hour, the single backwards jump disappears or multiplies, and pandas raises `ValueError`, for example `There are 2 dst switches when there should only be 1`. Keep a sequence number and restore recorded order before inferring.
  • In pandas 3.0, why might pd.Timestamp('2025-10-25 02:30', tz='Europe/Berlin') + pd.offsets.Day(1) raise?
    Day is a calendar day in pandas 3.0, so the result keeps the 02:30 wall-clock reading on 26 October, the night clocks fall back. That reading happens twice, so pandas cannot pick an instant and raises `ValueError`. Adding `pd.Timedelta(days=1)` instead gives exactly 24 hours later and never hits the problem.

  • Thinks tz_convert raises at the daylight-saving change
  • Believes ambiguous='infer' works on a single unpaired repeated reading
  • Expects a pytz exception class from pandas 3.0 by default
  • Reads ambiguous=True as meaning winter time
  • Assumes pd.offsets.Day(1) still equals 24 hours in pandas 3.0
  • Fixes every DST error with ambiguous='NaT' without counting lost rows

Assumes pandas 3.0: zoneinfo replaced pytz as the default, so ambiguous and nonexistent times raise ValueError instead of pytz exceptions, and offsets.Day became a calendar day rather than a fixed 24 hours.