Open In App

Pandas Series dt.year | Extract Year Part from DateTime Series

Last Updated : 06 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The dt.year attribute returns a Numpy array containing the year value of the DateTime Series Object

Example

Python3




import pandas as pd
sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30',
                '2010-4-22 09:25', '2019-11-8 02:22'])
  
idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
sr.index = idx
sr = pd.to_datetime(sr)
result = sr.dt.year
print(result)


Output

Day 1    2012
Day 2 2019
Day 3 2008
Day 4 2010
Day 5 2019
dtype: int64

Syntax

Syntax: Series.dt.year

Parameter : None

Returns: NumPy array with year value

How to Extract Year Value from DateTime Object in Pandas Series

To extract the year value of the DateTime object we use the Series.dt.year attribute of the Pandas library in Python.

Let us understand it better with an example:

Example:

In this example, we are using the Series.dt.year attribute of Pandas library to return the year of the datetime in the underlying data of the given Series object.

Python3




# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(pd.date_range('2012-12-12 12:12',
                             periods=5, freq='H'))
  
# Creating the index
idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
  
# set the index
sr.index = idx
  
# Print the series
print(sr)


Output:

Day 1   2012-12-12 12:12:00
Day 2 2012-12-12 13:12:00
Day 3 2012-12-12 14:12:00
Day 4 2012-12-12 15:12:00
Day 5 2012-12-12 16:12:00
dtype: datetime64[ns]

Now we print the year part of these timestamps using dt.year attribute.

Python3




# return the year
result = sr.dt.year
  
# print the result
print(result)


Output

Day 1    2012
Day 2 2012
Day 3 2012
Day 4 2012
Day 5 2012
dtype: int64

As we can see in the output, the Series.dt.year attribute has successfully accessed and returned the year of the DateTime in the underlying data of the given series object.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads