Pandas has extensive functionality for working with dates and times. The datetime module in Python’s standard library provides the basic building blocks, while Pandas builds on this with its own Timestamp and Timedelta types.
Converting to Datetime
To work with dates and times in a DataFrame, we often need to convert string representations of dates into Pandas datetime objects. This can be done using the pd.to_datetime() function.
import pandas as pd# Sample datadata = {"date": ["2023-01-01", "2023-02-01", "2023-03-01"], "value": [10, 20, 30]}df = pd.DataFrame(data)# Convert the 'date' column to datetimedf["date"] = pd.to_datetime(df["date"])df
date
value
0
2023-01-01
10
1
2023-02-01
20
2
2023-03-01
30
Extracting Date Components
Once we have a datetime column, we can easily extract components such as the year, month, day, etc.