PUBLISHED ON: JANUARY 30, 2021
Get year from a Date in Python
In this article, we will learn how to get the year from a given date in Python. We will use the built-in module available for getting date and time information and some custom codes as well to see them working. Let's first have a quick look over what are dates in Python.
Python Date
In Python, we can work on Date functions by importing a built-in module datetime
available in Python. We have date objects to work with dates. This datetime module contains dates in the form of year, month, day, hour, minute, second, and microsecond. The datetime module has many methods to return information about the date object. It requires date, month, and year values to compute the function. Date and time functions are compared like mathematical expressions between various numbers.
There are various ways in which we can get the year. We can get a year from a given input date, current date using date object. We will import date
class from datetime
module and will print the output. Look at the examples below.
Example: Get Year from the given Date
In this example, we import datetime module. Using datetime
object, we applied today()
function to extract the current date and then year()
to get only the year from the current date.
import datetime
year = datetime.datetime.today().year
print(year)
2021
Example: Get Year from the given Date Using now() Function
In this example, we import datetime module. Using datetime
object, we applied now()
function to extract the current date first and then year()
to get only the year from the current date.
import datetime
year = datetime.datetime.now().year
print(year)
2021
Conclusion
In this article, we learned to get the year from the current date using two datetime
functions. We used now().year()
and today().year()
to extract the year from the current date. We saw two examples of the implementation of these two functions.