Get year from DateTime Python

Get year from DateTime in Python

Being able to extract the year from a DateTime object in Python can be extremely helpful for feature engineering. In this post, I will walk through how to do this simply in multiple variations.

Stephen Allwright
Stephen Allwright

Being able to extract the year from a DateTime object in Python can be extremely helpful for feature engineering. In this post, I will walk through how to do this simply in multiple variations.

How to convert a DateTime in Python to the nearest year

Extracting the year from a DateTime object in Python is incredibly simple. All you need to do is call .year on the DateTime object and the year will be returned as an integer.

get year from date python

Get year from DateTime in Python

The most common way to get the year from a DateTime object in Python is to use .year which returns it as an integer, letโ€™s look at an example of this.

from datetime import datetime

date = datetime(2022,6,22,18,30,0)

year = date.year

print("Year:", year)
print(type(year))

"""
Output:

Year: 2022
<class 'int'>
"""

Get year from date as a string in Python

The previous example returned the year as an integer, but itโ€™s also possible to return this as a string. There are two date formats that can be returned, letโ€™s have a look at them.

from datetime import datetime

date = datetime(2022,6,22,18,30,0)

year_with_century = date.strftime("%Y")
year_without_century = date.strftime("%y")

print("Year:", year_with_century)
print(type(year_with_century))

print("Year:", year_without_century)
print(type(year_without_century))

"""
Output:

Year: 2022
<class 'str'>

Year: 22
<class 'str'>
"""

Get week number from datetime
Get month from date
Get day from datetime
Get year from date in Pandas

References

Python strftime documentation

Pandas

Stephen Allwright Twitter

I'm a Data Scientist currently working for Oda, an online grocery retailer, in Oslo, Norway. These posts are my way of sharing some of the tips and tricks I've picked up along the way.

Comments