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)
Extracted Hour= 17
Extracted Minute= 34
Source Code explanation
- Import datetime from datetime module.
- Get input from user in specified format.
- datetime.strptime() is stored in “time” which will convert string into datetime representation.
- Then used print command to get output of code.