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 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'> """
Fit Predict Newsletter
The simple weekly roundup of all the latest news, tools, packages, and use cases from the world of Data Science 📥