Python - How To Get Hour and Minutes From Datetime in Python

ID : 388

viewed : 87

Tags : PythonPython DateTime

vote vote

92

This tutorial will explain various methods to get hour and minute from the string containing date and time using the datetime module in Python. The datetime module provides classes for formatting and manipulating data and time.

Get Hour From datetime in Python Using the datetime.hour Attribute

The strptime() method of the datetime module in Python takes a string containing date, time, or both and returns a datetime object by parsing the string.

We can get a datetime object using the strptime() method by passing the string which contains date and time and get a datetime object. We can then get the hour and minute from the datetime object by its .hour and .minute attributes.

  • Method 1:
from datetime import *  time = datetime.strptime("03/02/21 16:30", "%d/%m/%y %H:%M") print("Time = {:d}:{:02d}".format(time.hour, time.minute)) 

Output:

Time = 16:30 
  • Method 2:
from datetime import *  time = datetime.strptime("03/02/21 16:30", "%d/%m/%y %H:%M") print("Time = %s:%s" % (time.hour, time.minute)) 

Output:

Time = 16:30 

  • Related HOW TO?