pd.to_datetime()
to_datetime converts text or numbers into real datetime values you can do date maths with.
In this page:
Syntax
df["date"] = pd.to_datetime(df["date"])
pd.to_datetime("2024-03-15")
pd.to_datetime()
pd.to_datetime parses strings such as "2024-03-15" into Timestamp objects, and a whole column into datetime64. Use format="%d/%m/%Y" for non-ISO layouts and errors="coerce" to turn bad dates into NaT.
The .dt accessor then exposes year, month, day and weekday.
Note:
NaT is the datetime equivalent of NaN.
Example: pd.to_datetime()
import pandas as pd
s = pd.Series(["2024-03-15", "2024-12-01", "not a date"])
d = pd.to_datetime(s, errors="coerce")
print(d)
print(d.dt.year.tolist())
print(pd.to_datetime("15/03/2024", format="%d/%m/%Y"))
# Output:
# 0 2024-03-15
# 1 2024-12-01
# 2 NaT
# dtype: datetime64[ns]
# [2024.0, 2024.0, nan]
# 2024-03-15 00:00:00
Related Topics
Common Mistakes
- Leaving dates as text
- Ambiguous day/month order without a format
- Ignoring NaT from invalid input
Chapter Summary
- to_datetime parses text into datetimes
- format controls the layout
- errors=coerce yields NaT
- .dt exposes date parts
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: