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 |
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 |
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 |
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 |
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 |
print(datetime.now().day) # 22
Further Resources
Please find some related tutorials below.
- How to Add Days, Months & Years to a datetime Object in Python (3 Examples)
- Add Hours, Minutes & Seconds to datetime Object in Python (3 Examples)
- Transform datetime Object to Date & Vice Versa in Python (2 Examples)
- All Python Programming Tutorials
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.