Transform datetime Object to Hours Minutes or Seconds in Python (3 Examples)
This article shows how to transform a datetime object to hours, minutes, and seconds in the Python programming language.
Importing datetime Module
To start with the examples, we first have to load the datetime module:
from datetime import datetime |
from datetime import datetime
Example 1: Return Hours from datetime Object
For the first example, we can use the strptime() function in combination with the hours attribute to extract the hours from our datetime object:
# get seconds print(datetime.strptime("25/12/22 18:45", "%d/%m/%y %H:%M").hour) # 0 |
# get seconds print(datetime.strptime("25/12/22 18:45", "%d/%m/%y %H:%M").hour) # 0
Example 2: Return Minutes from datetime Object
To return minutes from a date and time object, we apply the strptime() function combined with the minutes attribute:
# get minutes print(datetime.strptime("25/12/22 18:45", "%d/%m/%y %H:%M").minute) # 45 |
# get minutes print(datetime.strptime("25/12/22 18:45", "%d/%m/%y %H:%M").minute) # 45
Example 3: Return Seconds from datetime Object
And to convert our datetime object to seconds, we use strptime() function in combination with the seconds attribute:
# get hours print(datetime.strptime("25/12/22 18:45", "%d/%m/%y %H:%M").second) # 18 |
# get hours print(datetime.strptime("25/12/22 18:45", "%d/%m/%y %H:%M").second) # 18
Further Resources
Please find some related tutorials below.
- Set Unix Timestamp to datetime in Python (Example)
- 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)
- 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.