Sub topic 7
Parsing dates
This chapter assumes you can call read_csv and read_excel, know what a DataFrame and a dtype are, and have pandas 2.0 or later installed. The date_format argument does not exist in earlier versions.
A CSV file stores dates as plain text. Unless you ask otherwise, pandas loads a date column as strings (dtype object). Strings cannot be sorted by time, subtracted, resampled or grouped by month. Converting them to datetime64 at load time fixes this and also catches bad values early.
The default: dates stay text
Without any date arguments, read_csv does not guess that a column holds dates.
import pandas as pd
from io import StringIO
text = "id,signup\n1,2024-01-05\n2,2024-02-11\n"
plain = pd.read_csv(StringIO(text))
print(plain.dtypes)
parsed = pd.read_csv(StringIO(text), parse_dates=["signup"])
print(parsed.dtypes)
print(parsed["signup"].dt.month.tolist())The first frame has signup as object. The second has datetime64, so the .dt accessor works. parse_dates takes a list of column names (or positions). Only those columns are converted.
Declaring the format with date_format
Ambiguous strings such as 05/01/2024 can mean 5 January or 1 May. If you do not say which, pandas has to guess for you. Pass date_format with a strftime pattern and pandas parses every value the same way.
import pandas as pd
from io import StringIO
text = "id,when\n1,05/01/2024\n2,11/02/2024\n"
df = pd.read_csv(
StringIO(text),
parse_dates=["when"],
date_format="%d/%m/%Y",
)
print(df["when"].dt.strftime("%Y-%m-%d").tolist())The output is ['2024-01-05', '2024-02-11']. The common codes are %Y (four-digit year), %m (month), %d (day), %H, %M, %S (time) and %z (UTC offset such as +0100).
A format also makes parsing faster, because pandas skips format inference. For a large file this is a real saving.
When parsing fails
Here is the behavior that surprises people most. If any value in a column cannot be parsed, read_csv does not raise an error. It leaves the whole column as text.
import pandas as pd
from io import StringIO
text = "id,signup\n1,2024-01-05\n2,not a date\n3,2024-03-09\n"
df = pd.read_csv(StringIO(text), parse_dates=["signup"], date_format="%Y-%m-%d")
print(df["signup"].dtype)
df["signup"] = pd.to_datetime(df["signup"], format="%Y-%m-%d", errors="coerce")
print(df["signup"].dtype)
print(df["signup"].isna().sum())The first dtype is a text type, not datetime64. After pd.to_datetime(..., errors="coerce"), the bad value becomes NaT (not a time, the datetime version of NaN) and the column is datetime64. The final line prints 1.
Choose errors deliberately:
| `errors=` | Behavior on a bad value | Use when |
|---|---|---|
| `"raise"` (default) | Raises an exception | Bad data must stop the pipeline |
| `"coerce"` | Replaces it with `NaT` | You will count and inspect the bad rows |
| `"ignore"` | Removed in pandas 3 | Do not use |
Choosing a strategy
The right approach depends on what the file contains.
For files with several formats in one column, load the column as text and convert it afterward.
import pandas as pd
s = pd.Series(["2024-01-05", "05 Feb 2024", "March 9, 2024"])
dates = pd.to_datetime(s, format="mixed")
print(dates.dt.strftime("%Y-%m-%d").tolist())format="mixed" infers the format for each element separately. It is slower than a fixed format and can misread ambiguous day/month strings, so use it only when the data really is inconsistent.
Dates split across several columns
Some files store year, month and day in separate columns. The older parse_dates={"new": [...]} form of combining columns inside read_csv is deprecated. Combine them after loading instead. pd.to_datetime accepts a DataFrame whose columns are named year, month and day (and optionally hour, minute, second).
import pandas as pd
from io import StringIO
text = "year,month,day,value\n2024,1,5,10\n2024,2,11,20\n"
df = pd.read_csv(StringIO(text))
df["date"] = pd.to_datetime(df[["year", "month", "day"]])
df = df.drop(columns=["year", "month", "day"])
print(df.dtypes)Dates as the index
Time series work usually wants the dates as the index. Combine index_col with parse_dates.
import pandas as pd
from io import StringIO
text = "day,sales\n2024-01-01,5\n2024-01-02,7\n2024-01-03,6\n"
df = pd.read_csv(StringIO(text), index_col="day", parse_dates=["day"])
print(type(df.index).__name__)
print(df.loc["2024-01-02":"2024-01-03", "sales"].sum())The index is a DatetimeIndex, which allows slicing by date strings. The sum prints 13. Using parse_dates=True instead parses only the index column.
Time zones and UTC offsets
Strings with UTC offsets need care. If a column holds different offsets, pandas cannot put them in one timezone-naive dtype. Convert to UTC with utc=True, then to a local zone if you need one.
import pandas as pd
s = pd.Series(["2024-03-01T10:00:00+01:00", "2024-03-01T10:00:00+02:00"])
utc = pd.to_datetime(s, utc=True)
print(utc.tolist())
berlin = utc.dt.tz_convert("Europe/Berlin")
print(berlin.dt.hour.tolist())The two timestamps are an hour apart in UTC (09:00 and 08:00). Without utc=True, mixed offsets produce an object column or a warning, depending on the pandas version.
Dates in Excel files
Excel stores real dates as numbers with a date format, and read_excel converts those cells to datetime64 automatically. You do not need parse_dates for them. Dates typed as text, such as '05/01/2024 with a leading apostrophe or a text-formatted cell, load as strings and need the same conversion you use for CSV.
import pandas as pd
from io import BytesIO
source = pd.DataFrame({
"real": pd.to_datetime(["2024-01-05", "2024-02-11"]),
"text": ["05/01/2024", "11/02/2024"],
})
buffer = BytesIO()
source.to_excel(buffer, index=False, engine="openpyxl")
buffer.seek(0)
df = pd.read_excel(buffer)
print(df.dtypes)
df["text"] = pd.to_datetime(df["text"], format="%d/%m/%Y")
print(df["text"].dt.day.tolist())The real column arrives as datetime64. The text column arrives as text until you convert it. The last line prints [5, 11].
Common errors
- Column stays
object. One value did not match the format. Load as text, convert witherrors="coerce", and inspect theNaTrows. - Days and months swapped. An ambiguous format was guessed. Set
date_formatexplicitly. TypeErroraboutdate_format. You are on pandas 1.x. Upgrade, or convert after loading withpd.to_datetime.- Out-of-bounds dates. Very old or far-future years such as
9999-12-31can overflow the default nanosecond resolution in some versions. Convert witherrors="coerce"or keep those values as text. - Mixed-offset warning. Pass
utc=Truetopd.to_datetime.
Exercise
A CSV has a column ordered with values like 31/12/2023 and 01/02/2024, and a few rows contain the text TBD. Write the load step so that ordered ends up as datetime64 with NaT for TBD, and explain why you cannot rely on parse_dates alone.
Show answer
Load the file with df = pd.read_csv("orders.csv"), then run df["ordered"] = pd.to_datetime(df["ordered"], format="%d/%m/%Y", errors="coerce"). With parse_dates=["ordered"] and date_format="%d/%m/%Y", a single TBD value makes the parse fail, and read_csv then leaves the whole column as text without raising an error. The explicit to_datetime call with errors="coerce" turns TBD into NaT and converts the rest. Afterward, check df["ordered"].isna().sum() to confirm that only the TBD rows were affected.