Get Hour and Minutes From Datetime in Python

In this program , we are going to learn how to get the hours and minutes values from a datetime object of Python Datetime class. We often have need to extract hour, minute and seconds from the Datetime object.

Extract Hours and Minutes using strptime()

In this example, we are going to use the Python strptime() function from the datetime object.

from datetime import datetime
time = datetime.strptime("18/02/22 17:34", "%d/%m/%y %H:%M")
print("Extracted Hour=",time.hour)
print("Extracted Minute=",time.minute)

Output:

Extracted Hour= 17
Extracted Minute= 34

Source Code explanation

  1. Import datetime from datetime module.
  2. Get input from user in specified format.
  3. datetime.strptime() is stored in “time” which will convert string into datetime representation.
  4. Then used print command to get output of code.