Get Current Year, Month & Day in Python (3 Examples)
This article shows how to show the current day, month, and year in Python.
The post consists of these contents:
Let’s do this.
Introducing Example Data
Before we can start, we first need to import date from datetime:
from datetime import date # Load date from datetime
We’ll also have to create some example data:
my_date = date.today() # Get today's date print(my_date) # 2022-07-05
The previous output of the Python console shows our example data – since we want to extract the current attributes of a date, we use the date of today, of course.
Example 1: Get Current Year in Python
In the first example, I’ll demonstrate how to extract the current year of the today’s date.
For this, we can apply the year attribute of the date class, have a look at the following Python code:
current_year = my_date.year # Applying year attribute of date class print(current_year) # Print today's year # 2022
As you can see, we only get the number of the year returned.
Example 2: Get Current Month in Python
Example 2 demonstrates how to print only the month of the current date by using the month attribute:
current_month = my_date.month # Applying month attribute of date class print(current_month) # Print today's month # 7
The output above shows us that we have the seventh month of the year, in other words: July.
Example 3: Get Current Day in Python
Last but not least, I’ll demonstrate how to show only the current day of the date.
current_day = my_date.day # Applying day attribute of date class print(current_day) # Print today's day # 5
Like you may have expected, the code box above returns us that it’s the fifth day of our current month.
Video & Further Resources
I have recently published a video on my YouTube channel, which explains the Python codes of this article. You can find the video below.
Besides that, you might have a look at the related posts on https://statisticsglobe.com/. Please find some interesting articles on dates and times below:
- Get Day of Week from datetime in Python – Number & Name
- Get Current Date & Time in Python
- Get Current Time in Specific Timezone in Python
- Get Current Day of Week in Python – Number & Name
- The Python Programming Language
At this point you should have learned how to get the current year, month, and day in Python programming. If you have further questions, let me know in the comments.
This page was created in collaboration with Matthias Bäuerlen. Have a look at Matthias’ author page to get more information about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.