python get year from datetime column code example

Example 1: month from datetime pandas

#Exctract month and create a dedicated column df["Month"] from a 
#column in datetime format df["Date"]
df['Month'] = pd.DatetimeIndex(df['Date']).month

Example 2: select year from index

Pandas - extracting month and year from index

You can take below example, However you can have the details usage from Docs pandas.DatetimeIndex

Example DataFrame:

>>> df
                              name  age favorite_color  grade  birth_date
Willard Morris      Willard Morris   20           blue     88  01-02-1996
Al Jennings            Al Jennings   19            red     92  08-05-1997
Omar Mullins          Omar Mullins   22         yellow     95  04-28-1996
Spencer McDaniel  Spencer McDaniel   21          green     70  12-16-1995
1) To extract year:

>>> df['year'] = pd.DatetimeIndex(df['birth_date']).year
>>> df.head()
                              name  age favorite_color  grade  birth_date  year
Willard Morris      Willard Morris   20           blue     88  01-02-1996  1996
Al Jennings            Al Jennings   19            red     92  08-05-1997  1997
Omar Mullins          Omar Mullins   22         yellow     95  04-28-1996  1996
Spencer McDaniel  Spencer McDaniel   21          green     70  12-16-1995  1995
2) To extract month:

>>> df['month'] = pd.DatetimeIndex(df['birth_date']).month
>>> df.head()
                              name  age favorite_color  grade  birth_date  year  month
Willard Morris      Willard Morris   20           blue     88  01-02-1996  1996      1
Al Jennings            Al Jennings   19            red     92  08-05-1997  1997      8
Omar Mullins          Omar Mullins   22         yellow     95  04-28-1996  1996      4
Spencer McDaniel  Spencer McDaniel   21          green     70  12-16-1995  1995     12
3) To extract year_with_month:

>>> df['month_year'] = pd.to_datetime(df['birth_date']).dt.to_period('M')
>>> df
                              name  age favorite_color  grade  birth_date  year  month month_year
Willard Morris      Willard Morris   20           blue     88  01-02-1996  1996      1    1996-01
Al Jennings            Al Jennings   19            red     92  08-05-1997  1997      8    1997-08
Omar Mullins          Omar Mullins   22         yellow     95  04-28-1996  1996      4    1996-04
Spencer McDaniel  Spencer McDaniel   21          green     70  12-16-1995  1995     12    1995-12