Get the current year, month and day in Python


Get the current year, month and day in Python

📋 Table Of Content

In this post, we will learn how to use the datetime module to get the current day, month, or year in python.

Getting the current day, month and year

To get the day, month and year in python we can use the datetime module.

The datetime module provides classes to work with date and time. These classes help us to deal with dates and time or time intervals with a number of functions.

So to get the current year or month we have to first import the date class from the datetime module.

Next, create a date object and call the today() method from the date class. It will return us today's date.

from datetime import date

today_date = date.today()
print(today_date) // 2022-09-05

It returns the current date.

Now, once we get the current date, we can fetch the year, month, and day in string format like this.

from datetime import date

today_date = date.today()

print('Current Day:', today_date.day)
print('Current Month:', today_date.month)
print('Current Year:', today_date.year)

The output will be

Current Day: 5
Current Month: 9
Current Year: 2022