Python - Calculate the difference between two datetime.time objects Python - Calculate the difference between two datetime.time objects python-3.x python-3.x

Python - Calculate the difference between two datetime.time objects


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


This is how I did

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

output: 4.0


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