W3docs

Extracting just Month and Year separately from Pandas Datetime column

You can extract the month and year separately from a Pandas datetime column using the dt accessor.

You can extract the month and year separately from a Pandas datetime column using the dt accessor. Here's an example code snippet:

Extract the month and year separately from a Pandas datetime column using the dt accessor

import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'date': ['2022-01-01', '2022-02-01', '2022-03-01']})

# convert the date column to datetime
df['date'] = pd.to_datetime(df['date'])

# extract the month and year separately
df['month'] = df['date'].dt.month
df['year'] = df['date'].dt.year

# display the result
print(df)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

This will create a new column called 'month' and 'year' with the respective values.