Extract Day, Month & Year Separately from datetime Object in Python (3 Examples)
In this article you’ll learn how to extract the day, month, and year separately from a datetime object in the Python programming language.
The table of content is structured as follows:
Let’s dive into the Python code!
Import datetime Module & Create Example Data
As a first step, we have to import the datetime module into Python:
from datetime import datetime
In this example, we’ll use the present datetime using the now() command:
print(datetime.now()) # 2021-11-19 06:59:44.221036
Let’s extract the day, month, and year from this datetime object!
Example 1: Extract Day from datetime Object
This example uses the day attribute to get the day of a datetime object:
print(datetime.now().day) # 19
Example 2: Extract Month from datetime Object
In this example we’ll extract the month number of the present datetime.
To achieve this, we can use the month attribute as shown below:
print(datetime.now().month) # 11
Example 3: Extract Year from datetime Object
This example uses the year attribute to return the year of the present datetime in 4-digit format:
print(datetime.now().year) # 2021
Video, Further Resources & Summary
Do you need more explanations on how to extract specific parts from a datetime object in Python? Then you should have a look at the following YouTube video of Corey Schafer’s YouTube channel.
In the video, the speaker explains how to use the datetime module in Python.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you could have a look at some of the other tutorials on Statistics Globe:
This post has shown how to return days, months, and years separately from a datetime object in the Python programming language. In case you have further questions, you may leave a comment below.
This tutorial was created in collaboration with Gottumukkala Sravan Kumar. Please have a look at Gottumukkala’s author page to get more information about his academic background and the other articles he has written for Statistics Globe.