The dt accessor in pandas is used to access various properties of datetime objects in a Series. To extract the month from a datetime column, you can use the dt.month attribute.
Here’s an example:
import pandas as pd
# Sample DataFrame with a datetime column
data = {
'datetime': ['2023-10-01', '2023-10-15', '2023-11-05']
}
df = pd.DataFrame(data)
# Convert the 'datetime' column to datetime objects
df['datetime'] = pd.to_datetime(df['datetime'])
# Extract the month from the 'datetime' column
df['month'] = df['datetime'].dt.month
print(df)
In this example:
- The
datetimecolumn is converted to datetime objects usingpd.to_datetime(). - The month is extracted using
df['datetime'].dt.month, and a new columnmonthis created to store the extracted month values.
The resulting DataFrame will include the original datetime values along with the extracted month.
