Sub topic 3
Handling invalid and missing times with NaT
This chapter assumes you can build a Series or DataFrame, filter rows with a boolean mask, and call pd.to_datetime on a column. It covers what pandas stores when a time is missing or unreadable, and how to find and handle those values.
What NaT is
NaT stands for "Not a Time". It is the datetime counterpart of NaN. A datetime column keeps its datetime64 dtype when it holds NaT, so one bad value does not turn the column into text.
pandas produces NaT in two situations:
- The source value was already missing, such as
NoneorNaN. - Parsing failed and you asked pandas not to raise an error.
Choosing how parsing fails
pd.to_datetime has an errors argument. The default is "raise", which stops at the first value it cannot read. Passing errors="coerce" replaces each unreadable value with NaT and keeps going.
Use "raise" while you are cleaning data and want to know about every problem. Use "coerce" when you expect some bad values and plan to inspect them afterwards. Recent pandas versions deprecate errors="ignore", so avoid it in new code.
import pandas as pd
bad = pd.Series(["2024-01-05", "not a date"])
parsed = pd.to_datetime(bad, errors="coerce")
print(parsed)
print(parsed.isna())The first value becomes a Timestamp and the second becomes NaT. isna() returns False and then True.
Finding the rows that failed
Coercion hides the original text, so compare the parsed result with the raw input. A value is truly invalid only if it is NaT after parsing but present before. Rows that were already missing are not parse failures.
import pandas as pd
raw = pd.Series(["2024-01-05", "not a date", None, "2024-02-30"])
parsed = pd.to_datetime(raw, errors="coerce")
failed = raw[parsed.isna() & raw.notna()]
print(failed)This prints the entries at index 1 and 3. Index 2 is excluded because it was None from the start. "2024-02-30" fails because February has no 30th day.
NaT does not compare like other values
NaT follows the same rule as NaN: it is not equal to anything, including itself.
import pandas as pd
print(pd.NaT == pd.NaT)
print(pd.isna(pd.NaT))The first line prints False and the second prints True. Never filter with df["when"] == pd.NaT. It matches nothing. Use isna() or notna() instead.
How NaT spreads through calculations
Most operations on NaT return a missing value rather than an error. Components extracted with .dt become NaN, which turns integer results into floats. Subtracting a timestamp gives a NaT in the Timedelta result.
import pandas as pd
raw = pd.Series(["2024-01-05", "not a date", None, "2024-02-30"])
parsed = pd.to_datetime(raw, errors="coerce")
print(parsed.dt.month)
print(parsed - pd.Timestamp("2024-01-01"))parsed.dt.month shows 1.0 followed by NaN values, with dtype float64, because integers cannot hold NaN. The subtraction shows 4 days for the first row and NaT for the others.
Dropping or filling
Once you have located the missing values, you have three choices:
| Goal | Method | Effect |
|---|---|---|
| Remove incomplete rows | `df.dropna(subset=["when"])` | Rows with `NaT` in that column are deleted |
| Substitute a known date | `s.fillna(pd.Timestamp("2024-01-01"))` | `NaT` becomes the given timestamp |
| Carry a value forward | `s.ffill()` | `NaT` takes the previous valid timestamp |
Filling with a made-up date can distort durations and counts later. Prefer dropping, or keep the NaT and filter explicitly, unless a default is meaningful for your data. Forward fill suits ordered logs where a missing time means "same as before".
Exercise
A column parsed with errors="coerce" has 3 NaT values. How do you tell which of them came from unreadable text, and which were already empty in the source?
Show answer
Compare against the raw column. Rows where parsed.isna() is True and raw.notna() is True failed to parse. Rows where raw was already missing are not parse failures.
Exercise
Why does df["when"] == pd.NaT never select the missing rows, and what should you write instead?
Show answer
NaT is not equal to anything, including itself, so the comparison is False for every row. Use df["when"].isna() to select missing rows, or df["when"].notna() to keep valid ones.