Get Month, Year and Monthyear from date in pandas python

dt.year  is the inbuilt method to get year from date in Pandas Python.  strftime() function can also be used to extract year from date. month() is the inbuilt function in pandas python to get month from date. to_period() function is used to extract month year.  Let’s see how to

  • Get the year from any given date in pandas python
  • Get month from any given date in pandas
  • Get monthyear from date in pandas python

First lets create the dataframe

import pandas as pd
import numpy as np
import datetime

date1 = pd.Series(pd.date_range('2012-1-1 12:00:00', periods=7, freq='Y'))
df = pd.DataFrame(dict(date_given=date1))
print(df)

so the resultant dataframe will be

Get year from date in pandas python 1

 

Get the year from given date in pandas python using year function

Year function gets year value of the date

df['year_of_date'] = df['date_given'].dt.year
df

so the resultant dataframe will be

Get year from date in pandas python 2

 

Get the year from date in pandas python using strftime() function

strftime() function gets year from date as shown below.

df['year_of_date'] = df['date_given'].dt.strftime('%Y')
df

'%Y' represents the year value of the date. so the resultant dataframe will be

Get year from date in pandas python 2

 

Get Month from date in pandas python using month function

month function gets month value of the date

df['month_value'] = df['date_given'].dt.month
df

so the resultant dataframe will be

Get Month, Year and Monthyear from date in pandas python 3

 

 

Get MonthYear from date in pandas python using to_period() function

to_period() function takes (‘M’) as input gets monthyear from of the date

df['MonthYear_value'] = df['date_given'].dt.to_period('M')
df

so the resultant dataframe  with monthyear value calculated will be

Get Month, Year and Monthyear from date in pandas python 4

 

Get year from date in pandas python                                                                                                           Get year from date in pandas python

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.