Sub topic 7
Parsing dates
This chapter assumes you can run read_csv with a StringIO source, know what a dtype is, and have read the chapter on missing values. By default, read_csv loads date columns as plain text (object or string dtype). Text dates cannot be sorted by time, subtracted, or grouped by month. Parsing them at load time gives you real timestamps.
Why dates stay as text
pandas does not guess that a column holds dates unless you ask it to. The check below shows the default result.
import pandas as pd
from io import StringIO
text = "id,signup\n1,2024-01-05\n2,2024-02-11\n"
df = pd.read_csv(StringIO(text))
print(df.dtypes)The signup column is not a date type. The values look like dates, but pandas treats them as strings.
Parsing with parse_dates
Pass the column names to parse_dates. pandas then converts those columns to datetime64, the pandas timestamp type.
import pandas as pd
from io import StringIO
text = "id,signup\n1,2024-01-05\n2,2024-02-11\n"
df = pd.read_csv(StringIO(text), parse_dates=["signup"])
print(df.dtypes)
print(df["signup"].dt.month.tolist())The .dt accessor now works, so you can read parts such as month or dayofweek.
Day-first formats and date_format
A date such as 05/01/2024 is ambiguous. It can mean 5 January or 1 May. Without guidance, pandas assumes month first. Use date_format to state the exact layout with strftime codes: %d is day, %m is month, %Y is a four-digit year.
import pandas as pd
from io import StringIO
text = "id;price;date\n1;3,50;05/01/2024\n2;N/A;11/02/2024\n"
df = pd.read_csv(
StringIO(text),
sep=";",
decimal=",",
na_values=["N/A"],
parse_dates=["date"],
date_format="%d/%m/%Y",
index_col="id",
)
print(df.dtypes)
print(df["date"].tolist())The first date becomes 5 January 2024. An explicit format also makes parsing faster and stricter, because pandas does not have to infer the layout row by row.
Common errors
- Column stays as text. One value that does not fit the format, such as
"unknown"or"2024-13-01", can leave the whole column asobject. Add the marker tona_values, or fix the format. - Day and month swapped. No error is raised. Check a value where the day is above 12, such as
25/01/2024, to confirm the order. - Wrong column name.
parse_dates=["Date"]raises aValueErrorif the header isdate. Names are case-sensitive. - Mixed formats in one column. A single
date_formatcannot cover them. Load the column as text, then convert it withpd.to_datetime(df["col"], format="mixed").
Converting after loading
If parsing at load time is not possible, convert afterwards. errors="coerce" turns unparseable values into NaT, the missing-value marker for timestamps.
import pandas as pd
s = pd.Series(["2024-01-05", "unknown", "2024-02-11"])
dates = pd.to_datetime(s, format="%Y-%m-%d", errors="coerce")
print(dates)
print(dates.isna().sum())Counting NaT values after a coerced conversion shows how many rows failed to parse.
Exercise
A file uses semicolons and holds the line 7;25/12/2024, with columns id and day. Write the read_csv arguments that load day as a day-first date. Then name the one value in this row that proves the order is right.
Show answer
Use pd.read_csv(StringIO(text), sep=";", parse_dates=["day"], date_format="%d/%m/%Y"). The value 25 can only be a day, because no month is 25. The result is 25 December 2024.