How do you get just the time from a datetime in python?

I have a field that shows time as 1900-01-01 00:05:00 but I want to show it as just 00:05:00 i.e. just five minutes.

I have been looking at the python documentation and it is driving me crazy. From the question How do I find the time difference between two datetime objects in python? it looks like is should be something do with timedelta but I am not getting any closer to a solution. The question Converting Date/Time to Just Time suggests you can just use a format tag but that is not working for me. I also looked at converting date time to string without success, I know this is something simple but I have looked at hundreds of pages looking for something simple. All help would be appreciated.

asked Mar 29, 2015 at 2:01

1

Say you have a Datetime object now:

now.time().strftime('%H:%M:%S')

answered Mar 29, 2015 at 2:06

satorusatoru

30.2k29 gold badges87 silver badges138 bronze badges

0

Load the string with strptime() and get the time() component:

>>> from datetime import datetime
>>> s = "1900-01-01 00:05:00"
>>> dt = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
>>> dt.time().isoformat()
'00:05:00'

Here we are dumping the time with isoformat() in ISO 8601 format, but you can also dump the datetime.time back to string with strftime():

>>> dt.time().strftime("%H:%M:%S")
'00:05:00'

answered Mar 29, 2015 at 2:07

How do you get just the time from a datetime in python?

alecxealecxe

447k114 gold badges1037 silver badges1163 bronze badges

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 datetime

from datetime import datetime

datetime_str = "24AUG2001101010"

datetime_obj = datetime.strptime(datetime_str, 

                                 "%d%b%Y%H%M%S")

print(datetime_obj)

time = datetime_obj.time()

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 datetime

from datetime import datetime

datetime_str = "31OCT2020231032"

datetime_obj = datetime.strptime(datetime_str, "%d%b%Y%H%M%S")

print("date time : {}".format(datetime_obj))

time = datetime_obj.time()

print("Time : {}".format(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 datetime

from datetime import datetime

datetime_str = "10JAN300123000"

datetime_obj = datetime.strptime(datetime_str,

                                 "%d%b%Y%H%M%S")

print("date time : {}".format(datetime_obj))

time = datetime_obj.time()

print("Time : {}".format(time)) 

minute = time.minute

print("Minute : {}".format(minute))

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 datetime

from datetime import datetime

datetime_str = "32JAN2022102356"

try:

    datetime_obj = datetime.strptime(datetime_str,

                                     "%d%b%Y%H%M%S")

    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


How do I extract time from a datetime object in Python?

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

How can I get time from datetime?

How to Get the Current Time with the datetime Module. To get the current time in particular, you can use the strftime() method and pass into it the string ”%H:%M:%S” representing hours, minutes, and seconds.

How do I get only time in Python?

You can use the below code snippet to get the current time in python. First, use the datetime. now() from the DateTime library and then format it using the strftime("%H:%M:%S") to get only the time information.

How do I change datetime to just time?

Extract time only from datetime with formula Select a blank cell, and type this formula =TIME(HOUR(A1),MINUTE(A1), SECOND(A1)) (A1 is the first cell of the list you want to extract time from), press Enter button and drag the fill handle to fill range. Then only time text has been eatraced from the list.