Sub topic 2
Parsing text into datetimes with to_datetime
This chapter assumes you can create a pandas Series or DataFrame and select a column. It also assumes you know what a string is and what the standard datetime module does. Here you will turn text columns into real datetime values with pd.to_datetime.
Why parse at all
Dates read from CSV files or APIs usually arrive as strings. Pandas stores them with the object dtype, so you can't compute durations, extract the month, or slice by date. pd.to_datetime converts them to datetime64[ns], which is the dtype pandas uses for timestamps.
Parsing with an explicit format
The safest approach is to tell pandas the layout of your text with the format argument. The codes follow the standard strftime conventions: %Y is a four-digit year, %m the month, %d the day, %H the hour, and %M the minute.
import pandas as pd
df = pd.DataFrame({
"when": ["2024-03-01 09:30", "2024-03-02 14:45", "2024-03-05 08:00"],
"amount": [10, 25, 40],
})
df["when"] = pd.to_datetime(df["when"], format="%Y-%m-%d %H:%M")
print(df.dtypes)The when column now has dtype datetime64[ns]. With an explicit format, pandas parses every value the same way and fails loudly if one does not match. Without it, pandas infers the layout from the first values, which can hide mistakes.
Handling bad values with errors
By default, one unparseable value makes the whole call raise an exception. Pass errors="coerce" to replace bad values with NaT (Not a Time), the missing-value marker for datetimes. The next chapter covers NaT in detail.
Ambiguous dates and dayfirst
A string like 03/04/2024 could be March 4 or April 3. Pandas assumes month first unless you pass dayfirst=True.
bad = pd.Series(["2024-01-05", "not a date"])
parsed = pd.to_datetime(bad, errors="coerce")
print(parsed)
print(parsed.isna())
print(pd.to_datetime("03/04/2024", dayfirst=True))The first print shows 2024-01-05 followed by NaT. The isna() call returns False then True, so you can count or filter the failures. The last line prints 2024-04-03, because dayfirst=True reads the string as day/month/year.
Choosing between format and dayfirst
| Situation | Best option |
|---|---|
| Every value has the same known layout | `format="..."` |
| Layout is ISO 8601 (`2024-03-01`) | No extra arguments needed |
| Slash dates written day first | `dayfirst=True`, or better, an explicit `format` |
| A few corrupted values you want to inspect | `errors="coerce"`, then check `isna()` |
An explicit format is preferable to dayfirst because it states the whole layout and rejects values that do not fit it.
Common mistakes
- Relying on inference for ambiguous data. If a file mixes
03/04/2024with other layouts, pandas may read some rows one way and some another. Specify the format. - Using coerce and never checking.
errors="coerce"hides problems. Compare the NaT count before and after to see how many values failed. - Forgetting to assign the result.
pd.to_datetime(df["when"])returns a new Series. You must assign it back to keep it.
Exercise
A column contains the strings "15/03/2024" and "01/04/2024", both written day/month/year. Which call parses them correctly, and why is it safer than relying on defaults?
Show answer
Use pd.to_datetime(col, format="%d/%m/%Y"). It states that the day comes first, so "01/04/2024" is read as 1 April instead of January 4. It also raises an error for any value that does not match the layout.
Exercise
What does pd.to_datetime(pd.Series(["2024-01-05", "oops"]), errors="coerce") return for the second element?
Show answer
NaT, the missing-value marker for datetimes. The Series keeps dtype datetime64[ns], and isna() returns True for that position.