Sub topic 6
Parsing dates with pd.to_datetime
This chapter assumes you can build a DataFrame, select columns, and have met object dtype and pd.to_numeric. Here you will turn date text into real datetime64 values, and handle strings that do not parse.
Why parse dates
A column of date strings has dtype object. You can't subtract dates, group by month, or sort chronologically with it. Text sorts alphabetically, which only matches time order for formats like 2024-01-05. pd.to_datetime converts the text to datetime64[ns], and the result supports the .dt accessor and date arithmetic.
Basic conversion
Pass the column and, whenever you know it, the format.
import pandas as pd
df = pd.DataFrame({
"date": ["2024-01-05", "2024-02-10", "bad"],
})
df["date"] = pd.to_datetime(df["date"], format="%Y-%m-%d", errors="coerce")
print(df["date"])
print(df.dtypes)The first two values become timestamps. The value "bad" becomes NaT, which stands for "not a time" and is the datetime version of NaN.
The format argument
The format argument uses strftime codes. These are the common ones:
| Code | Meaning | Example |
|---|---|---|
| `%Y` | 4-digit year | 2024 |
| `%m` | month number | 01 |
| `%d` | day of month | 05 |
| `%H:%M:%S` | hour, minute, second | 13:45:00 |
| `%b` | abbreviated month name | Jan |
Giving a format has two benefits. Parsing is faster, because pandas doesn't have to guess for each value. It also removes ambiguity. Without a format, pandas infers one from the data, and a string like 03/04/2024 could mean 3 April or 4 March.
Day-first and month-first dates
If you can't give a format, tell pandas which order to use.
s = pd.Series(["03/04/2024", "25/12/2024"])
print(pd.to_datetime(s, dayfirst=True))With dayfirst=True, both values read as day/month/year. Without it, pandas assumes month first, and 25/12/2024 triggers a warning or a failure because there is no month 25. Prefer an explicit format over dayfirst when the layout is fixed.
Choosing the errors setting
to_datetime has the same errors options as to_numeric.
| Setting | Behavior on a bad value |
|---|---|
| `"raise"` (default) | Raises an exception. |
| `"coerce"` | Returns `NaT` for that value. |
Use "raise" while exploring, so problems are loud. Use "coerce" when you accept missing dates and plan to inspect them afterward.
raw = pd.Series(["2024-01-05", "not a date", None])
parsed = pd.to_datetime(raw, format="%Y-%m-%d", errors="coerce")
failed = raw[parsed.isna() & raw.notna()]
print(failed)The last two lines find values that were present in the raw data but became NaT. The original None is excluded because it was already missing.
Working with the result
Once the column is datetime64, the .dt accessor gives you its parts.
dates = pd.to_datetime(pd.Series(["2024-01-05", "2024-02-10"]))
print(dates.dt.year.tolist())
print(dates.dt.month.tolist())
print(dates.dt.day_name().tolist())
print((dates.iloc[1] - dates.iloc[0]).days)Subtracting two timestamps gives a Timedelta, which has attributes such as .days.
Common errors
- Parsing without a format. Mixed layouts are guessed, and some values may be read wrongly without any error. Specify
formatfor fixed layouts. - Using
coerceand never checking. Bad dates quietly becomeNaT. Always compare against the raw column, as shown above. - Swapping day and month.
01/02/2024is valid either way, so pandas won't complain. Check a few known rows by hand. - Expecting
astype.astype("datetime64[ns]")works on clean data, but it has noerrors="coerce"option. Useto_datetimefor messy text.
Diagram of the workflow
Exercise
The Series ["31/01/2024", "15/02/2024", "oops"] holds day/month/year text. Write code that converts it to datetime64, turns the bad entry into NaT, and lists the raw values that failed.
Show answer
raw = pd.Series(["31/01/2024", "15/02/2024", "oops"]) parsed = pd.to_datetime(raw, format="%d/%m/%Y", errors="coerce") failed = raw[parsed.isna() & raw.notna()] print(failed) This prints "oops". The format "%d/%m/%Y" fixes the day-first order, and the final mask keeps only values that were present but failed to parse.