Sub topic 13
Common pitfalls and how to debug them
This chapter assumes you know pd.to_datetime, the .dt accessor, DatetimeIndex selection, and tz_localize and tz_convert. Most date bugs in pandas come from a few causes: text that parsed differently than you meant, values that silently became NaT, and time zones that don't match. This chapter shows each one and a quick way to find it.
Start with a debugging routine
Check three things before you suspect your logic: the dtype, the count of missing values, and the time zone.
Pitfall 1: ambiguous formats
A string like 03/04/2024 can mean 3 April or 4 March. Pandas guesses, and the guess can differ from what you intended. Pass format= so the meaning is fixed and a mismatch fails loudly.
import pandas as pd
s = pd.Series(["03/04/2024", "13/04/2024"])
print(pd.to_datetime(s, format="%d/%m/%Y"))Without format=, pandas infers the layout from the first value and then raises an error on 13/04/2024, because 13 is not a month. With dayfirst=True the guess is steered, but an explicit format is the safer choice.
Pitfall 2: silent NaT from errors="coerce"
errors="coerce" keeps the pipeline running by turning bad text into NaT. The cost is that the bad rows disappear into missing values. Always look at what was lost.
raw = pd.Series(["2024-01-05", "5 Jan", "oops"])
parsed = pd.to_datetime(raw, format="%Y-%m-%d", errors="coerce")
print(parsed.isna().sum())
print(raw[parsed.isna()])Indexing the raw column with the NaT mask shows exactly which strings failed. Fix the format or clean those values, then parse again.
Pitfall 3: mixed time zones in one column
Strings with different UTC offsets can't share one fixed-offset dtype. Pandas may fall back to object and warn, or raise an error in newer versions. Convert everything to UTC while parsing.
mixed = pd.Series(["2024-03-01 09:00+00:00", "2024-03-01 09:00+05:00"])
fixed = pd.to_datetime(mixed, utc=True)
print(fixed)
print(fixed.dt.tz)After this, fixed has dtype datetime64[ns, UTC]. Use tz_convert when you need local display.
Pitfall 4: naive versus aware comparisons
A timestamp without a time zone (naive) and one with a time zone (aware) can't be ordered against each other.
naive = pd.Timestamp("2024-03-01 09:00")
aware = pd.Timestamp("2024-03-01 09:00", tz="UTC")
try:
print(naive < aware)
except TypeError as e:
print("TypeError:", e)
print(naive.tz_localize("UTC") < aware)Decide which zone the naive values were recorded in, attach it with tz_localize, and only then compare. Calling tz_localize on values that already have a zone raises an error. Use tz_convert for those.
Other quick checks
| Symptom | Likely cause | Check |
|---|---|---|
| `.dt` raises `AttributeError` | Column is still `object` | `df.dtypes` |
| Partial-string slice returns wrong rows or errors | Index isn't sorted | `ts.index.is_monotonic_increasing` |
| `resample` raises `TypeError` | Index isn't a `DatetimeIndex` | `type(ts.index)` |
| Off-by-hours results | Naive data treated as UTC, or the reverse | `ts.index.tz` |
| Rolling `"3D"` fails | Index is not sorted or not datetime-like | Sort, then check the index type |
Exercise
A column parsed with pd.to_datetime(col, errors="coerce") shows 40 NaT values. What single expression shows the original strings that failed?
Show answer
Keep the raw column and index it with the mask: col[pd.to_datetime(col, errors="coerce").isna()]. This lists the original text for each row that became NaT. If some of those rows were already missing in the raw data, also filter with col.notna() so you see only real parse failures.
Exercise
You compare ts_naive.index[0] < ts_utc.index[0] and get a TypeError. Name two steps that resolve it and say which one to use if the naive data was recorded in New York.
Show answer
Either attach a zone to the naive values with tz_localize, or convert the aware values to naive after tz_convert. For New York data, use tz_localize("America/New_York") on the naive index, then tz_convert("UTC") so both sides share one zone.