'Python - Calculate the difference between two datetime.time objects

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.



Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[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

Solution 4:[4]

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)

Solution 5:[5]

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]')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brylie Christopher Oxley
Solution 2 iAnas
Solution 3 Roham Rafii
Solution 4 Michel de Ruiter
Solution 5 Ciril Achenkunju