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

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

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

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


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. Required fields are marked *

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