Sub topic 13
Common pitfalls and how to debug them
This chapter collects the mistakes that most often break date and time code in pandas. It then gives a repeatable way to find the cause when results look wrong. It assumes you can use pd.to_datetime, the .dt accessor, a DatetimeIndex, resample, and tz_localize/tz_convert as covered in earlier chapters. Examples target pandas 2.x.
Why time bugs are hard to see
Most datetime bugs do not raise errors. A column stays as strings, a month and day swap places, or a NaT quietly drops out of a sum. The output looks plausible and is wrong. So the habit that matters most is to inspect dtypes, missing counts, and ranges before you trust a result.
The flowchart below is the order I use when a time-based result looks off.
Ambiguous and mixed date formats
The string 03/04/2024 is 4 March in the United States and 3 April in much of the world. By default to_datetime reads it month first. If you know the data is day first, say so.
In pandas 2.x, when you give no format, pandas infers one from the first non-missing value and applies it to the whole column. A later value that does not fit raises an error. Older versions guessed per element, which could silently mix conventions.
import pandas as pd
raw = pd.Series(["03/04/2024", "25/04/2024"])
try:
pd.to_datetime(raw)
except ValueError as err:
print("inferred month-first, second value failed")
print(pd.to_datetime(raw, format="%d/%m/%Y"))The first call infers month/day/year from 03/04/2024, so 25/04/2024 fails because there is no month 25. The explicit format parses both values as day/month/year.
An explicit format= is also faster, because pandas skips format guessing. Use dayfirst=True only for quick work. A format string states the full contract and fails loudly when the data breaks it.
Numbers need the same care. pd.to_datetime(1709290000) treats the integer as nanoseconds since 1970 and gives a date within the first seconds of 1970. For Unix seconds, pass unit="s".
NaT: when coercion hides your errors
errors="coerce" turns anything unparseable into NaT (Not a Time). That keeps a pipeline running, but it also erases evidence. A typo and a legitimately missing value end up looking the same.
Before you coerce, compare the raw column to the parsed one so you can list what failed. The difference between "was missing" and "failed to parse" is raw.notna() & parsed.isna().
raw = pd.Series(["2024-01-05", "2024-13-01", "n/a", None])
parsed = pd.to_datetime(raw, errors="coerce", format="%Y-%m-%d")
failed = raw[raw.notna() & parsed.isna()]
print(failed)
print("missing from source:", raw.isna().sum())
print("failed to parse:", len(failed))This prints 2024-13-01 and n/a as the failures, and reports one value that was already missing. Report failures instead of dropping them, or you may lose a whole month of data that used a different format.
Two more NaT facts cause confusion:
NaT == NaTisFalse, likeNaN. Use.isna(), not==.- Datetime arithmetic with
NaTgivesNaT, so one bad value makes adiff()result missing at two positions: the bad row and the row after it.
A value outside the supported range, such as the year 9999 as a "no end date" placeholder, raises OutOfBoundsDatetime under the default nanosecond resolution. With errors="coerce" it becomes NaT, which may not be what you want for an open-ended interval. Handle those sentinel values explicitly.
Time zone mistakes
Time zone errors fall into four groups.
Mixed UTC offsets. Strings with different offsets cannot share one datetime64[ns, tz] dtype. Without utc=True, pandas returns an object column of Python datetimes, with a warning in recent versions. Most .dt operations then fail or run slowly.
mixed = pd.Series(["2024-03-01 10:00+01:00", "2024-07-01 10:00+02:00"])
parsed = pd.to_datetime(mixed, utc=True)
print(parsed)
print(parsed.dt.tz_convert("Europe/Berlin"))Parse to UTC first, then convert to the zone you need for display or grouping.
Naive versus aware comparisons. A naive timestamp has no zone, and an aware one does. Ordering comparisons between them raise an error.
naive = pd.Timestamp("2024-03-01 10:00")
aware = pd.Timestamp("2024-03-01 10:00", tz="UTC")
try:
print(naive < aware)
except TypeError as err:
print("TypeError:", err)Using the wrong method. tz_localize attaches a zone to naive values and fails on values that already have one. tz_convert changes the zone of aware values and fails on naive ones. If you hit a TypeError mentioning "already tz-aware" or "naive", you called the wrong one. Check s.dt.tz (or index.tz): None means naive.
Daylight saving gaps and overlaps. When clocks move forward, some local times never exist. When they move back, some happen twice. tz_localize refuses to guess.
local = pd.Series([1], index=pd.to_datetime(["2024-03-10 02:30"]))
try:
local.tz_localize("America/New_York")
except Exception as err:
print(type(err).__name__)
fixed = local.tz_localize("America/New_York", nonexistent="shift_forward")
print(fixed)The time 02:30 on 10 March 2024 does not exist in New York, because clocks jumped from 02:00 to 03:00. nonexistent="shift_forward" moves it to 03:00. For the opposite case, a repeated hour in November, use the ambiguous argument. ambiguous="NaT" marks repeated times as missing, and ambiguous="infer" works when the data is ordered and every repeated hour appears.
Timedelta components versus totals
A Timedelta stores one duration, but its attributes expose components. .days and .seconds are parts of the duration, not conversions of the whole.
gap = pd.Timestamp("2024-03-03 06:00") - pd.Timestamp("2024-03-01 00:00")
print(gap.days)
print(gap.seconds)
print(gap.total_seconds())The output is 2, 21600, and 194400.0. The .seconds value is only the leftover seconds after removing whole days. This gives wrong results for any gap of 24 hours or more. For a Series, use .dt.total_seconds() and divide by 3600 for hours, as in the earlier chapter.
Indexing and slicing traps
Unsorted index. Partial-string slicing assumes the index is sorted. With an unsorted DatetimeIndex, a slice whose bounds are not exact index entries can raise a KeyError. When it does not, the result cannot be relied on.
ts = pd.Series(
[1, 2, 3],
index=pd.to_datetime(["2024-03-05", "2024-03-01", "2024-03-03"]),
)
try:
print(ts.loc["2024-03-02":"2024-03-04"])
except KeyError:
print("KeyError: index is not sorted")
print(ts.sort_index().loc["2024-03-02":"2024-03-04"])Make sort_index() part of building any time-indexed series. Time-based rolling("3D") has the same requirement and raises an error if the index is not monotonic.
Day string versus Timestamp bounds. A partial string such as "2024-03-04" covers the whole day, so a slice ending at that string includes every row on 4 March. A slice ending at pd.Timestamp("2024-03-04") stops at midnight and drops the rest of the day.
Duplicate timestamps. ts.loc["2024-03-02"] on a day with several rows returns a Series, not a scalar. Code that expects one value then fails far from the cause.
Resampling surprises
resample("W") uses weeks that end on Sunday and, by default, labels each bin by its right edge. A date you expect in "the week of 1 January" is labeled 7 January. Empty bins are also created for gaps, and each aggregation fills them differently.
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-20"])
s = pd.Series([1.0, 2.0, 3.0], index=idx)
print(s.resample("W").sum())
print(s.resample("W").mean())The week ending 14 January has no data. sum() reports 0.0 there, and mean() reports NaN. A zero that means "nothing recorded" can be mistaken for a real measurement. Use s.resample("W").sum(min_count=1) to get NaN for empty bins.
Frequency aliases also changed in pandas 2.2. Month, quarter, and year ends are now "ME", "QE", and "YE", and "H" and "T" became "h" and "min". The old spellings raise a FutureWarning and are slated for removal. Treat warnings as a to-do list.
A quick audit helper
When you inherit a dataset, run one function that prints the facts above in a single place.
def audit_times(s):
print("dtype:", s.dtype)
if pd.api.types.is_datetime64_any_dtype(s):
print("time zone:", s.dt.tz)
print("NaT count:", s.isna().sum())
print("range:", s.min(), "to", s.max())
print("sorted:", s.is_monotonic_increasing)
else:
print("not a datetime column, parse it first")
audit_times(pd.Series(["2024-01-05", "2024-01-06"]))
audit_times(pd.to_datetime(pd.Series(["2024-01-06", "2024-01-05"])))The first call reports a non-datetime column. The second shows a datetime column with no time zone and sorted: False, which tells you to call sort_index or sort_values before slicing or rolling.
Symptom lookup table
| Symptom | Likely cause | Fix |
|---|---|---|
| Column dtype is `object` after parsing | Mixed offsets or failed parse | `utc=True` or explicit `format` |
| Month and day swapped | Ambiguous slash dates | `format="%d/%m/%Y"` |
| Rows vanish from totals | `NaT` from `errors="coerce"` | Compare raw and parsed, list failures |
| `TypeError` comparing times | Naive versus aware | Localize or convert both to one zone |
| `NonExistentTimeError` or `AmbiguousTimeError` | Daylight saving change | `nonexistent=` or `ambiguous=` |
| Wrong hour counts for long gaps | Used `.seconds` | Use `.total_seconds()` |
| `KeyError` on a date slice | Unsorted index | `sort_index()` |
| Zeros in empty periods | `sum()` on empty bins | `sum(min_count=1)` |
Exercise
A column of strings like "01/02/2024" and "15/02/2024" was parsed with pd.to_datetime(col, errors="coerce") and 40% of the result is NaT. Explain the likely cause and write the fix.
Show answer
Without a format, pandas infers month/day/year from the first value, so every value with a day above 12 (such as 15/02/2024) fails and coerce turns it into NaT. The data is day-first. Fix it with pd.to_datetime(col, format="%d/%m/%Y", errors="coerce"), then check that raw.notna() & parsed.isna() is empty.
Exercise
An aware Series in UTC is compared against pd.Timestamp("2024-06-01") and raises a TypeError. Name two correct ways to fix the comparison.
Show answer
Make both sides the same kind. Either localize the timestamp, as in pd.Timestamp("2024-06-01", tz="UTC") or pd.Timestamp("2024-06-01").tzlocalize("UTC"), or remove the zone from the Series with s.dt.tzlocalize(None) after converting it to the zone you intend. Keeping both sides aware is safer, because dropping the zone discards information.