We all regularly observe the date and time, which are crucial measurements. As programmers, we frequently need to fiddle with dates and times for various tasks like recording birth dates and calculating the disparity between dates in days. Many a time we want to access the current date and perform some operations on it to get some results. In this article, we are going to learn how to get the current year in python.
What is DateTime Module?
To get things done quickly and with clear and simple syntax, Python has a tonne of built-in libraries at our disposal in addition to a tonne of external libraries created by developers. Datetime is one such module; it is a built-in Python module that deals with date and time.
The datetime provides a straightforward syntax and simplifies dealing with dates. Let's examine some potential methods for obtaining the current year with this module.
How to Get Current Year in Python?
There are two methods to get the current year in Python. Let's look at them.
1) By Using today() method
We use the today() method inside the date class to fetch today's date. This class is present inside the datetime module.
For example:
import datetime today = datetime.date.today() print(today)
Output:
2022-06-22
Now to just get the year from this returned date object we have two ways. Let's see them one by one.
a) Accessing the year attribute
Utilizing the datetime module is the quickest way to determine the current year. We can directly access the year attribute of the returned object.
For example:
import datetime today = datetime.date.today() year = today.year print(year)
Output:
2022
b) With srtftime() function
The strfttime() function in Python is another method for obtaining the current year. The function strftime() takes a string specifying the date format as the argument. It returns the given date as a string in the provided format.
We will pass "% Y" to strftime() to get the year of the date object.
For example:
import datetime today = datetime.date.today() year = today.strftime("%Y") print(year)
Output:
2022
2) By Using now() method
To get the current date and time we can also use the now() method present inside the datetime class inside the datetime module. Then to get the current year, we can either access the year attribute or use the strftime() method
For example:
import datetime today = datetime.datetime.now() #accessing the year attribute year1 = today.year print(year1) #using the strftime() method year2 = today.strftime("%Y") print(year2)
Output:
2022 2022
Conclusion
Python with its huge collection of built-in libraries makes a tedious task a very easy job. In this article, we learned two methods to get the current year in python which can be easily done with the datetime module.
Check how to extract the year from the date in R Programming.