← Back to Pandas Course | Chapter 10: Time Series | Lesson 1 of 7

pd.to_datetime()

to_datetime converts text or numbers into real datetime values you can do date maths with.

In this page:

  1. pd.to_datetime()
Syntax
python
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()

python
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
  1. Leaving dates as text
  2. Ambiguous day/month order without a format
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.