subtract two times in python

I have two datetime.time values, exit and enter and I want to do something like:

duration = exit - enter

However, I get this error:

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time

How do I do this correctly? One possible solution is converting the time variables to datetime variables and then subtruct, but I'm sure you guys must have a better and cleaner way.


Solution 1:

Try this:

from datetime import datetime, date

datetime.combine(date.today(), exit) - datetime.combine(date.today(), enter)

combine builds a datetime, that can be subtracted.

Solution 2:

Use:

from datetime import datetime, date

duration = datetime.combine(date.min, end) - datetime.combine(date.min, beginning)

Using date.min is a bit more concise and works even at midnight.

This might not be the case with date.today() that might return unexpected results if the first call happens at 23:59:59 and the next one at 00:00:00.

Solution 3:

instead of using time try timedelta:

from datetime import timedelta

t1 = timedelta(hours=7, minutes=36)
t2 = timedelta(hours=11, minutes=32)
t3 = timedelta(hours=13, minutes=7)
t4 = timedelta(hours=21, minutes=0)

arrival = t2 - t1
lunch = (t3 - t2 - timedelta(hours=1))
departure = t4 - t3

print(arrival, lunch, departure)

Solution 4:

The python timedelta library should do what you need. A timedelta is returned when you subtract two datetime instances.

import datetime
dt_started = datetime.datetime.utcnow()

# do some stuff

dt_ended = datetime.datetime.utcnow()
print((dt_ended - dt_started).total_seconds())