Answers for "python datetime extract year"

22

python year from date

import datetime
date = '2021-05-21 11:22:03'
datem = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
print(datem.day)        # 25
print(datem.month)      # 5
print(datem.year)       # 2021
print(datem.hour)       # 11
print(datem.minute)     # 22
print(datem.second)     # 3
Posted by: Guest on May-21-2021
0

extract only year from date python

df['year'] = pd.DatetimeIndex(df['date']).year
Posted by: Guest on June-16-2021
0

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
Posted by: Guest on November-06-2020

Code answers related to "python datetime extract year"

Python Answers by Framework

Browse Popular Code Answers by Language