Extract hour from time

In this section, we will extract hours from extracted time from the DateTime object, all the 3 steps are the same as in the previous example, In this example, we will add the .hour method to extract hours from DateTime object.

We have to extract time, so the next part is to extract hours from DateTime object, by calling the .hour method.

Syntax : .hour

Return : It will return the hour from timestamp.

Below is the implementation:

Python3




# import important module
import datetime
from datetime import datetime
  
# Create datetime string
datetime_str = "31OCT2020231032"
  
# call datetime.strptime to convert
# it into datetime datatype
datetime_obj = datetime.strptime(datetime_str, "%d%b%Y%H%M%S")
  
# It will print the datetime object
print("date time : {}".format(datetime_obj))
  
# extract the time from datetime_obj
time = datetime_obj.time()
  
# it will print time that
# we have extracted from datetime obj
print("Time : {}".format(time)) 
  
# extract hour from time
hour = time.hour
print("Hour : {}".format(hour))


Output: 

date time : 2020-10-31 23:10:32
Time : 23:10:32
Hour : 23

Extract time from datetime in Python

In this article, we are going to see how to extract time from DateTime in Python.

In Python, there is no such type of datatype as DateTime, first, we have to create our data into DateTime format and then we will convert our DateTime data into time. A Python module is used to convert the data into DateTime format, but in the article, we will be using the datetime module to do this task.

Syntax: datetime.strptime()

Parameters : 

  • arg: It can be integer, float, tuple, Series, Dataframe to convert into datetime as its datatype
  • format: This will be str, but the default is None. The strftime to parse time, eg “%d/%m/%Y”, note that “%f” will parse all the way up to nanoseconds.

e.g – > format = “%Y%b%d%H%M%S”

e.g., datetime_obj = datetime.strptime(“19022002101010″,”%d%m%Y%H%M%S”) # It will return the datetime object.

Similar Reads

Extract time from DateTime object

In this section, we will extract time from DateTime object....

Extract hour from time

...

Extract minutes and second from time

In this section, we will extract hours from extracted time from the DateTime object, all the 3 steps are the same as in the previous example, In this example, we will add the .hour method to extract hours from DateTime object....

Determine time, if the date note falls in the range

...