Open In App

Extract time from datetime in Python

Last Updated : 31 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Extract time from 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 module
import datetime
from datetime import datetime
  
# Create datetime string
datetime_str = "24AUG2001101010"
  
# 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(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) 


Output: 

2001-08-24 10:10:10
10:10:10

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 minutes and second from time

In this example, we will add the .minute, .second method to extract minutes and seconds from DateTime object.

Python3




# import important module
import datetime
from datetime import datetime
  
# Create datetime string
datetime_str = "10JAN300123000"
  
# 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 minute from time
minute = time.minute
print("Minute : {}".format(minute))
  
# extract second from time
second = time.second
print("Second : {}".format(second))


Output

date time : 3001-01-10 23:00:00
Time : 23:00:00
Minute : 0
Second : 0

Determine time, if the date note falls in the range

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 module
import datetime
from datetime import datetime
  
# Create datetime string
datetime_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



Previous Article
Next Article

Similar Reads

Python DateTime - DateTime Class
DateTime class of the DateTime module as the name suggests contains information on both dates as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day. But unlike the date class, the objects of the DateTime cl
5 min read
How to convert a Python datetime.datetime to excel serial date number
This article will discuss the conversion of a python datetime.datetime to an excel serial date number. The Excel "serial date" format is actually the number of days since 1900-01-00. The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string r
3 min read
How to Fix - "datetime.datetime not JSON serializable" in Python?
In this article, we are going to learn how to fix the error "datetime.datetime not JSON serializable" in Python. datetime.datetime is a class in the Python datetime module that represents a single point in time. This class is not natively supported by the JSON (JavaScript Object Notation) format, which means that we cannot serialize a datetime.date
4 min read
Pandas Series dt.time | Extract Time from Time Stamp in Series
The Series.dt.time attribute returns a NumPy array containing time values of the timestamps in a Pandas series. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime
2 min read
Pandas Series dt.date | Extract Date From DateTime Objects
The dt.date attribute extracts the date part of the DateTime objects in a Pandas Series. It returns the NumPy array of Python datetime.date objects, mainly the date part of timestamps without information about the time and timezone. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '201
2 min read
Pandas Series dt.year | Extract Year Part from DateTime Series
The dt.year attribute returns a Numpy array containing the year value of the DateTime Series Object Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) result
2 min read
Pandas Series dt.month | Extract Month Part From DateTime Series
The dt.month attribute returns a NumPy array containing the month of the DateTime in the underlying data of the given Series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = id
2 min read
Pandas Series dt.day | Extract Day Part from DateTime Series
Pandas dt.day attribute returns a NumPy array containing the day value of the DateTime in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] # set th
2 min read
Pandas Series dt.week | Extract Week Number from DateTime Series
Pandas dt.week attribute returns a NumPy array containing the week ordinal of the year in the underlying data of the given DateTime Series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
2 min read
Pandas Series dt.minute | Extract Minute from DateTime Series in Pandas
Pandas Series.dt.minute attribute returns a NumPy array containing the minutes of the DateTime in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
2 min read
Practice Tags :