Get month and Year from Date in Pandas - Python

Get month and Year from Date in Pandas - Python

If you have a date column in a Pandas DataFrame and you want to extract the month and year, you can use the dt accessor. Here's how you can do it:

import pandas as pd # Sample data df = pd.DataFrame({ 'date': ['2022-01-10', '2021-12-20', '2023-03-15'] }) # Convert the 'date' column to a datetime dtype df['date'] = pd.to_datetime(df['date']) # Extract month and year df['month'] = df['date'].dt.month df['year'] = df['date'].dt.year print(df) 

Output:

 date month year 0 2022-01-10 1 2022 1 2021-12-20 12 2021 2 2023-03-15 3 2023 

Now, the DataFrame has two new columns: 'month' and 'year', which contain the extracted month and year values, respectively.

If you want the month name instead of the month number, you can use:

df['month_name'] = df['date'].dt.strftime('%B') 

This will give you month names like "January", "February", etc.


More Tags

navigation-drawer character-encoding bootstrap-treeview wkhttpcookiestore mode email-parsing job-scheduling lambdaj command-pattern continuum

More Programming Guides

Other Guides

More Programming Examples