How is the dt accessor used to extract the month from the datetime column?

QuestionsQuestions4 SkillsProHandling Time Series DataAug, 06 2025
0284

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:

  1. The datetime column is converted to datetime objects using pd.to_datetime().
  2. The month is extracted using df['datetime'].dt.month, and a new column month is created to store the extracted month values.

The resulting DataFrame will include the original datetime values along with the extracted month.

0 Comments

no data
Be the first to share your comment!