Getting the current year is a common requirement in many Python applications, from generating copyright notices to filtering data. The standard way to accomplish this is by using the built-in datetime module, which provides a rich set of tools for working with dates and times.
This guide will demonstrate the most common methods for retrieving the current year, both as an integer and as a formatted string, and will clarify the subtle differences between the datetime.now() and datetime.today() methods.
Method 1: Using datetime.now().year (Integer)
The most common and straightforward way to get the current year is to use the datetime.now() method to get a datetime object representing the current moment, and then access its .year attribute.
Solution:
from datetime import datetime
current_datetime = datetime.now()
current_year = current_datetime.year
print(current_year)
print(f"The type of current_year is: {type(current_year)}")Output (will be the current year):
2025
The type of current_year is: <class 'int'>Method 2: Using datetime.today().year (Integer)
The datetime.today() method provides an alternative way to get the current local datetime. Like now(), it returns a datetime object from which you can access the .year attribute.
Solution:
from datetime import datetime
current_year = datetime.today().year
print(current_year)Output (will be the current year):
2025Method 3: Using strftime() to Get the Year as a String
If you need the year as a string, for example, for concatenation or display purposes, the .strftime() (string format time) method is the perfect tool. It allows you to format a datetime object into a string using specific format codes.
%Y: Four-digit year (e.g., "2024")%y: Two-digit year (e.g., "24")
Solution:
from datetime import datetime
now = datetime.now()
year_4_digit = now.strftime('%Y')
year_2_digit = now.strftime('%y')
print(f"Four-digit year (string): '{year_4_digit}' (type: {type(year_4_digit)})")
print(f"Two-digit year (string): '{year_2_digit}' (type: {type(year_2_digit)})")Output (will be the current year):
Four-digit year (string): '2025' (type: <class 'str'>)
Two-digit year (string): '25' (type: <class 'str'>)Key Difference: now() vs. today()
Conclusion
| Your Goal | Recommended Method | Result Type |
|---|---|---|
| Get the current year as an integer. | datetime.now().year |
int |
| Get the four-digit year as a string. | datetime.now().strftime('%Y') |
str |
| Get the two-digit year as a string. | datetime.now().strftime('%y') |
str |
By using the datetime module, you can easily and reliably retrieve the current year in the format that best suits your application's needs.