Sub topic 3
Handling invalid and missing times with NaT
This chapter assumes you can build a pandas Series or DataFrame, filter rows with boolean masks, and call pd.to_datetime on a column. It covers NaT, the marker pandas uses for a missing or invalid datetime. You will see where NaT comes from, how it behaves in comparisons and arithmetic, and how to find, count, fill, or drop it.
What NaT is
NaT stands for "Not a Time". It is the datetime counterpart of NaN. A column of dtype datetime64 can hold real timestamps and NaT together without changing dtype. NaT is stored as a special reserved value inside the column, so the column stays a fast datetime column and does not fall back to object.
pd.NaT is a single object. It also stands in for missing values in Timedelta and Period data.
import pandas as pd
s = pd.Series(pd.to_datetime(["2024-01-01", None, "2024-03-01"]))
print(s)
print(s.dtype)
print(type(pd.NaT))The None in the input becomes NaT with no extra work. The dtype remains a datetime64 dtype.
Where NaT comes from
NaT appears in a few common ways:
- Missing input.
None,NaN, empty strings, and the text"NaT"all parse toNaT, even with the defaulterrors="raise". - Invalid input with
errors="coerce". Text that cannot be parsed becomesNaT. - Impossible calendar dates, such as
"2024-02-30", when parsing witherrors="coerce". - Operations on existing
NaTvalues, such as subtracting two timestamps when one is missing. - Edge effects, such as the first row of
diff()orshift().
The default errors="raise" stops at the first bad value. That is often what you want while developing, because it tells you which value broke the assumption.
try:
pd.to_datetime(["2024-01-05", "oops"], format="%Y-%m-%d")
except ValueError as err:
print("parse failed:", err)With errors="coerce", parsing never fails. Every problem value is quietly replaced.
raw = pd.Series(["2024-01-05", "not a date", None, "2024-02-30"])
parsed = pd.to_datetime(raw, errors="coerce")
print(parsed)Only the first element survives. "not a date" is invalid text, None is missing, and February 30 is not a real date.
Telling missing values from failed parses
After errors="coerce", you can no longer tell a value that was missing from the start from one that failed to parse. Both are NaT. To separate them, compare against the original column.
failed = parsed.isna() & raw.notna()
print(raw[failed])
print("failed:", failed.sum(), "missing:", raw.isna().sum())failed is true only where the result is NaT but the input was not missing. This gives you the exact strings that need attention, such as a different format, a typo, or a placeholder like "unknown".
How NaT behaves
Comparisons
NaT follows the same rule as NaN: it is not equal to anything, including itself. Do not test for it with ==.
print(pd.NaT == pd.NaT)
print(pd.isna(pd.NaT))
s = pd.Series(pd.to_datetime(["2024-01-01", None, "2024-03-01"]))
print(s > pd.Timestamp("2024-02-01"))
print(s != pd.Timestamp("2024-01-01"))
print(s.isna())Results:
NaT == NaTisFalse.pd.isnareturnsTrue.s > cutoffisFalsefor theNaTrow, so a filter such asdf[df["when"] > cutoff]silently drops rows with missing times.s != valueisTruefor theNaTrow, so a filter written with!=keeps them.
Use isna() and notna() when you mean "is missing". When you filter by date, decide explicitly what should happen to the missing rows.
Arithmetic
Any arithmetic that involves NaT returns NaT, or NaN when the result is a number. The missing value spreads through the calculation.
deadline = pd.Series(pd.to_datetime(["2024-03-01", "2024-03-10", None]))
start = pd.Series(pd.to_datetime(["2024-02-20", None, "2024-03-01"]))
gap = deadline - start
print(gap)
print(gap.dt.days)Only the first row has a real Timedelta of 10 days. The other two rows are NaT. After .dt.days, the column holds 10.0, NaN, and NaN, and the dtype is float because integers cannot hold NaN.
Aggregation, sorting, and grouping
Most summary operations skip NaT by default:
min()andmax()ignore it.count()counts only real timestamps, whilelen()andsizecount every row.sort_values()putsNaTlast. Passna_position="first"to change that.groupbyon a datetime column drops rows whose key isNaTunless you passdropna=False.value_counts()leaves outNaTunless you passdropna=False.
print(s.min(), s.max())
print(s.count(), len(s))
print(s.sort_values(na_position="first"))The last point matters for reports. A group-by total over dates can be smaller than the overall total, because rows with NaT dates were left out without any warning.
NaT and the .dt accessor
The .dt accessor works on columns that contain NaT. Numeric components, such as month or dayofweek, become floats with NaN. Text components, such as day_name(), return missing values for those rows.
print(s.dt.month)
print(s.dt.day_name())
print(s.dt.month.astype("Int64"))The first line shows floats, 1.0, NaN, 3.0. If you need whole numbers, convert with the nullable integer dtype "Int64" (capital I). It stores integers and keeps a missing marker, <NA>, in the empty slot.
Filling and dropping
Your choice depends on what the missing time means. Three options cover most cases.
Drop the rows
Use this when a row is meaningless without its time.
events = pd.DataFrame({
"when": pd.to_datetime(["2024-03-01", None, "2024-03-03"]),
"value": [10, 20, 30],
})
clean = events.dropna(subset=["when"])
print(clean)Use subset so that missing values in other columns do not remove rows by accident.
Fill with a known value
If you know the real time, or a documented default, use fillna. The replacement must be a timestamp, not a string with a different meaning.
filled = events["when"].fillna(pd.Timestamp("2024-03-02"))
print(filled)Carry values forward or backward
In ordered data, a missing time can often be taken from its neighbours. ffill() copies the previous timestamp, and bfill() copies the next one.
print(events["when"].ffill())
print(events["when"].bfill())Only do this when it is truthful. A forward-filled timestamp makes the record look as if it happened at the same moment as the previous one, which changes durations and rolling windows.
NaT in a DatetimeIndex
An index can contain NaT, but it causes trouble. Partial string selection such as ts.loc["2024-03"] and slicing depend on a sorted, fully valid index. Drop or repair the missing times before calling set_index, then sort.
ts = (
events.dropna(subset=["when"])
.set_index("when")["value"]
.sort_index()
)
print(ts.loc["2024-03-01":"2024-03-03"])A short debugging routine
When a datetime column produces surprising results, work through these checks in order:
- Count the missing values:
df["when"].isna().sum(). - If you used
errors="coerce", compare against the raw column to find the failed parses, as in the earlierfailedmask. - Print a few of the failing raw strings. Look for a different separator, a trailing time zone, or a placeholder word.
- Check the
formatstring against a value that parsed correctly. - Compare row counts before and after each filter, group-by, or merge, to see where
NaTrows disappeared. - Decide on drop, fill, or keep, and write the decision down in a comment.
Summary table
| Situation | What happens with NaT | What to do | Column |
|---|---|---|---|
| Equality test `x == pd.NaT` | Always `False` | Use `isna()` or `notna()` | |
| Filter `df["when"] > cutoff` | `NaT` rows are excluded | Add `\ | df["when"].isna()` if they should stay |
| Subtracting timestamps | Result is `NaT` | Check `isna()` on the result | |
| `.dt.month` and similar | Float column with `NaN` | Convert with `astype("Int64")` | |
| `groupby` on dates | `NaT` rows dropped | Use `dropna=False` if needed | |
| `errors="coerce"` | Bad text becomes `NaT` | Count and inspect failures |
Exercise
A DataFrame column raw holds strings such as "2024-05-01", "", and "May 1st". You run df["when"] = pd.to_datetime(df["raw"], errors="coerce"). Write one expression that gives the rows where the text was present but failed to parse, and explain why df["when"].isna() alone is not enough.
Show answer
Use df[df["when"].isna() & df["raw"].notna() & (df["raw"] != "")]. The empty string is treated as missing by to_datetime, so it becomes NaT, but notna() on the raw text still counts it as present, which is why the extra != "" test is needed. df["when"].isna() alone is not enough because it is true for both missing input and failed parses, so you could not tell a blank cell from a value like "May 1st" that needs a new format.
Exercise
Given s = pd.Series(pd.to_datetime(["2024-01-01", None, "2024-03-01"])), what do (s > pd.Timestamp("2024-02-01")).sum() and (s != pd.Timestamp("2024-02-01")).sum() return, and why do they differ from what you might expect?
Show answer
The first returns 1, because only 2024-03-01 is later than the cutoff, and the comparison is False for NaT. The second returns 3, because 2024-01-01 and 2024-03-01 differ from the cutoff, and NaT is also "not equal" to everything, so it counts as True. Comparisons with NaT do not mean "unknown". They return fixed answers, so check for missing values explicitly.