Get Year, Month & Day Separately from datetime Object in Python (3 Examples)

On this site you’ll see how to extract the year, month, and day separately from a datetime object in Python.

Creating Example Data & Loading datetime Module

At first, we have to load the datetime module into Python:

from datetime import datetime

For the examples, we’ll take the present datetime by using the now() command:

print(datetime.now())
# 2022-03-22 17:28:45.326251

Example 1: Get Year from datetime Object

In this case, we can use the year attribute to extract the year of our present datetime in 4-digit format:

print(datetime.now().year)
# 2022

Example 2: Get Month from datetime Object

To extract the month number of the present datetime we have to use the month attribute:

print(datetime.now().month)
# 3

Example 3: Get Day from datetime Object

And to get the day of the datetime object, we can apply the day attribute:

print(datetime.now().day)
# 22

 

Further Resources

Please find some related tutorials below.

 

Matthias Bäuerlen Python Programmer

Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top