How to get a previous year in Python
In this tutorial, we are going to learn about how to get the previous year in Python.
Getting the previous year
To get the previous year in Python, first we need to access the current year using the date.today().year
property and subtract it with minus -1
.
The year
property returns the current year in four-digit(2023) string format according to the user’s local time, to get the previous year we are subtracting it with -1
.
Here is an example:
from datetime import date
previous_year = date.today().year -1
print(previous_year)
Output:
2022
In the example above, first we imported date
class from the datetime
module then accessed the current year using the date.today().year
for previous year we subtracted it with minus -1
.