Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the difference between two 24 hour times?

Tags:

python

pandas

Is there a simple way in pandas to tell the difference between 24 hour times as follows:

9:45 17:10

The difference is 7 hours and 25 minutes which is 445 minutes.

like image 278
graffe Avatar asked Sep 30 '16 09:09

graffe


2 Answers

I think you can also use the Python standard library datetime.datetime without installing the pandas.

>>> t1 = datetime.datetime.strptime('09:45', '%H:%M')
>>> t2 = datetime.datetime.strptime('17:10', '%H:%M')
>>> t1
datetime.datetime(1900, 1, 1, 9, 45)
>>> t2
datetime.datetime(1900, 1, 1, 17, 10)
>>> td = t2 - t1
>>> td.total_seconds()
26700.0
>>> str(td)
'7:25:00'
like image 154
bwangel Avatar answered Oct 02 '22 22:10

bwangel


Sure:

>>> from pandas import Timestamp
>>> Timestamp('9:45')    
Timestamp('2016-09-30 09:45:00')
>>> Timestamp('17:10')
Timestamp('2016-09-30 17:10:00')
>>> Timestamp('17:10') - Timestamp('9:45')
Timedelta('0 days 07:25:00')
>>> td = Timestamp('17:10') - Timestamp('9:45')
>>> td
Timedelta('0 days 07:25:00')

And if you really need the time in minutes:

>>> td.seconds/60
445
>>>

Edit

Just double-checked the documentation, and the seconds attribute of a Timedelta object returns: Number of seconds (>= 0 and less than 1 day).

So, to really be safe if you want the minutes, use:

>>> td.delta # returns the number of nanoseconds   
26700000000000
>>> td.delta * 1e-9 / 60
445.0
like image 40
juanpa.arrivillaga Avatar answered Oct 02 '22 22:10

juanpa.arrivillaga