When using Python, there are a number of ways to extract the year from a date in Python. The easiest way to get the year from a date is to access the “year” attribute of a date or datetime object.
from datetime import datetime
currentDateTime = datetime.now()
print(currentDateTime.year)
#Output:
2022
You can also use the strftime function to get the year of a datetime variable in Python.
from datetime import datetime
currentDateTime = datetime.now()
print(currentDateTime.strftime("%Y"))
#Output:
2022
When working in Python, many times we need to create variables which represent dates and times. When creating and displaying values related to dates, sometimes we need to display the current date.
With Python, we can easily extract the year from a date.
The Python datetime module has many great functions which allow us to interact with date and datetime objects easily.
The easiest way to get the year is to access the “year” attribute.
The “year” attribute returns an integer representing the year of the date.
Below shows you how to access the “year” attribute to extract the year from a datetime variable in Python.
from datetime import datetime
currentDateTime = datetime.now()
print(currentDateTime.year)
#Output:
2022
Another way to get the current year in Python is with the strfttime() function. strftime() accepts a string representing the format of a date and returns the date as a string in the given format.
To get the year of the date object with strftime(), pass “%Y”.
Below is an example of how to use strftime function to get the year from a date in Python.
from datetime import datetime
currentDateTime = datetime.now()
print(currentDateTime.strftime("%Y"))
#Output:
2022
Hopefully this article has been useful for you to learn how to get the year from a date or datetime object in Python using the datetime module.