29

I have two datetime.time objects and I want to calculate the difference in hours between them. For example

a = datetime.time(22,00,00)
b = datetime.time(18,00,00)

I would like to be able to subtract these so that it gives me the value 4.

user3080600
  • 1,159
  • 2
  • 10
  • 21

5 Answers5

47

To calculate the difference, you have to convert the datetime.time object to a datetime.datetime object. Then when you subtract, you get a timedelta object. In order to find out how many hours the timedelta object is, you have to find the total seconds and divide it by 3600.

# Create datetime objects for each time (a and b)
dateTimeA = datetime.datetime.combine(datetime.date.today(), a)
dateTimeB = datetime.datetime.combine(datetime.date.today(), b)
# Get the difference between datetimes (as timedelta)
dateTimeDifference = dateTimeA - dateTimeB
# Divide difference in seconds by number of seconds in hour (3600)  
dateTimeDifferenceInHours = dateTimeDifference.total_seconds() / 3600
user3080600
  • 1,159
  • 2
  • 10
  • 21
12

This is how I did

a = '2200'
b = '1800'
time1 = datetime.strptime(a,"%H%M") # convert string to time
time2 = datetime.strptime(b,"%H%M") 
diff = time1 -time2
diff.total_seconds()/3600    # seconds to hour 

output: 4.0

iAnas
  • 431
  • 1
  • 6
  • 9
3

I got my result from this problem:

a='2017-10-10 21:25:13'

b='2017-10-02 10:56:33'

a=pd.to_datetime(a)

b=pd.to_datetime(b)

c.total_seconds()/3600

but in series that wont work:

table1['new2']=table1['new'].total_seconds()/3600
Roham Rafii
  • 2,793
  • 7
  • 34
  • 44
0

Aside, but this might bother more users finding this question...

To calculate the difference between pandas columns, better is not to have time as type datetime.time in the first place, but as numpy.timedelta64 instead (duration since midnight). One way to fix this:

from datetime import datetime, date, time
for c in df.select_dtypes('object'):
    if isinstance(df[c][0], time):
        df[c] = df[c].apply(lambda t: datetime.combine(date.min, t) - datetime.min)
Michel de Ruiter
  • 6,263
  • 5
  • 48
  • 64
-1
import pandas as pd
a='2017-10-10 21:25:13'
b='2017-10-02 10:56:33'
a=pd.to_datetime(a)
b=pd.to_datetime(b)

(a-b).astype('timedelta64[h]')
  • 1
    See "[Explaining entirely code-based answers](https://meta.stackoverflow.com/q/392712/128421)". While this might be technically correct, it doesn't explain why it solves the problem or should be the selected answer. We should educate along with helping solve the problem. – the Tin Man Mar 22 '22 at 05:09
  • This does not even answer the question, as the values are `datetime`, not `time`. – Michel de Ruiter May 05 '22 at 12:00