We will get the year from a
datetime object. Basically,
datetime is a module that consists of classes to deal with date and time. We can create, store, access, format the date, and much more.
Get Year From a
datetime Object in Python
The technique to get the year from a
datetime object is pretty simple. The
datetime object has certain attributes like the year, month, day, hour, minutes and seconds, etc. (depending on the format of input date).
We will access the year attribute of the
datetime object, and get the year from the date. In this example, we will get the year from today’s date (present date). For a clearer example, we output today’s date, which includes day, month, and year. Then we access the year attribute of the
datetime object and output it.
# python 3.x import datetime date = datetime.date.today() print("Date is:", date) year = date.year print("Year of the Date is:", year)
Date is: 2021-12-05 Year of the Date is: 2021