To get the current day, month, and year in python we can use the datetime class from the datetime module that provides different classes to deal with date and time. To begin with, let’s import the datetime module.
from datetime import datetime
As you can see we also added from keyword with datetime that imports only datetime class from datetime module. For further explanation, there are two datetime in the above script in which the one that is next to import keyword is importing datetime module and another is importing datetime class from the module.
After importing the datetime module and class we can access or print the current date.
currentDate = datetime.now() print(currentDate) # Output: 2022-11-07 17:41:15.241680
datetime.now() returns today’s date with time. Since we assigned
datetime.now() to variable currentDate, it has all the attributes that belong to the datetime class. Let’s access current day
currentDate.day # Output: 7 # Type: <class 'int'>
To access the current month we can use the month attribute
currentDate.month # Output: 11 # Type: <class 'int'>
Similarly to access the current year we can use the year attribute
currentDate.year # Output: 2022 # Type: <class 'int'>
This article demonstrates getting the current day, month, and year in python. Python datetime module has a datetime class that provides attributes to access the current day, month, and year.