Extract time from datetime in Python

31 Aug, 2021
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.
In this section, we will extract time from DateTime object.
We make our string into DateTime object, now we extract time from our DateTime object, by calling .time() method.
Syntax : .time()
Returns : It will return the time from the datetime object
Below is the implementation:
Python3
# import important moduleimport datetimefrom datetime import datetime  # Create datetime stringdatetime_str = "24AUG2001101010"  # call datetime.strptime to convert# it into datetime datatypedatetime_obj = datetime.strptime(datetime_str,                                  "%d%b%Y%H%M%S")  # It will print the datetime objectprint(datetime_obj)  # extract the time from datetime_objtime = datetime_obj.time()    # it will print time that # we have extracted from datetime objprint(time) 
Output: 
2001-08-24 10:10:10
10:10:10
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 moduleimport datetimefrom datetime import datetime  # Create datetime stringdatetime_str = "31OCT2020231032"  # call datetime.strptime to convert# it into datetime datatypedatetime_obj = datetime.strptime(datetime_str, "%d%b%Y%H%M%S")  # It will print the datetime objectprint("date time : {}".format(datetime_obj))  # extract the time from datetime_objtime = datetime_obj.time()  # it will print time that# we have extracted from datetime objprint("Time : {}".format(time))   # extract hour from timehour = time.hourprint("Hour : {}".format(hour))
Output: 
date time : 2020-10-31 23:10:32
Time : 23:10:32
Hour : 23
In this example, we will add the .minute, .second method to extract minutes and seconds from DateTime object.
Python3
# import important moduleimport datetimefrom datetime import datetime  # Create datetime stringdatetime_str = "10JAN300123000"  # call datetime.strptime to# convert it into datetime datatypedatetime_obj = datetime.strptime(datetime_str,                                 "%d%b%Y%H%M%S")  # It will print the datetime objectprint("date time : {}".format(datetime_obj))  # extract the time from datetime_objtime = datetime_obj.time()  # it will print time that we# have extracted from datetime objprint("Time : {}".format(time))   # extract minute from timeminute = time.minuteprint("Minute : {}".format(minute))  # extract second from timesecond = time.secondprint("Second : {}".format(second))
Output: 
date time : 3001-01-10 23:00:00
Time : 23:00:00
Minute : 0
Second : 0
If Date doesn’t fall in the range, then the code will give us a ‘ValueError”.  In order to determine the time with this error, we can do is to use exception statements and tell the user that you have entered the wrong date and you can’t get the time from that date, because that date never existed, so how to the time should be existed in that date.
Python3
# import important moduleimport datetimefrom datetime import datetime  # Create datetime stringdatetime_str = "32JAN2022102356"try:        # 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))except:    print("You have entered Incorrect Date, please enter a valid date")
Output:
You have entered Incorrect Date, please enter a valid date
Picked
Python datetime-program
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list