subtract two times in python
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())
Solution 5
You have two datetime.time objects so for that you just create two timedelta using datetime.timedetla and then substract as you do right now using "-" operand. Following is the example way to substract two times without using datetime.
enter = datetime.time(hour=1) # Example enter time
exit = datetime.time(hour=2) # Example start time
enter_delta = datetime.timedelta(hours=enter.hour, minutes=enter.minute, seconds=enter.second)
exit_delta = datetime.timedelta(hours=exit.hour, minutes=exit.minute, seconds=exit.second)
difference_delta = exit_delta - enter_delta
difference_delta is your difference which you can use for your reasons.
Related videos on Youtube
Chaggster
Updated on June 10, 2021Comments
-
Chaggster almost 3 years
I have two
datetime.time
values,exit
andenter
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 todatetime
variables and then subtruct, but I'm sure you guys must have a better and cleaner way. -
swalog over 10 yearsIf you know from your domain that two
datetime.time
objectsa
andb
are from the same day, and thatb > a
, then the operationb - a
has perfect meaning. -
Akavall about 10 yearsTo @IgnacioVazquez-Abrams point, one could use, say,
datetime(1,1,1,0,0,0)
instead ofdate.today()
. -
naught101 about 9 yearsEven if they aren't the same day, it still makes fine sense. At least as much sense as
arctan(0) = (0, pi, 2pi, ...)
, but we just don't care about any of those values after the first. So,4:00 - 20:00
is8:00
- it's also (32:00
,56:00
, ... ), but who cares? -
Ignacio Vazquez-Abrams about 9 years
-
orokusaki over 8 yearsDon't name a
datetime
exit
, sinceexit
is a built-in function. -
mtoloo almost 8 yearsusing python 2.7, I don't have
combine
method in mydatetime
module:AttributeError: 'module' object has no attribute 'combine'
-
gruszczy almost 8 yearsmtoloo: There is
datetime
module and it has adatetime
object inside. The object inside hascombine
method. If you are simply importingdatetime
(like this:import datetime
), then what you need to do later is thisdatetime.datetime.combine
. -
Sean almost 8 yearsFurthermore, Python doesn't even stay consistent. If a - b is meaningless for two time objects, then how it that a > b or a < b behaves as it does? The comparison is already assuming same day, otherwise it is completely broken. Since the assumption is made for comparison, it is entirely consistent to make the same assumption for difference operations.
-
Sean almost 8 yearsor date.min -> datetime.date(1, 1, 1)
-
ramwin about 7 yearsThere is a very rare case when you call this function at some time like 23:59:59:9999. In that case, the
date.today()
before and thedate.today()
later will return a different value. It would be better to give the valuedate.today()
to a variable. -
ramwin about 7 yearsAgree with you.
-
aj.toulan over 6 yearsSaying it's meaningless is subjective, but I see where you're coming from. Adding two times together seems to be a meaningless representation to me. I think subtracting two time values should return a timedelta. If that timedelta happens to be negative, so be it. What I want to know is why python can't add or subtract a timedelta from a time to return a new time value.
-
Pushpak Dagade about 6 yearsThanks. This is very clean and better than all the answers here - stackoverflow.com/questions/3096953/…
-
dejanualex over 5 yearsIt is possible to convert the timedelta object back to datetime ? I mean we have difference_delta .seconds(), is there any way to get back a datetime or time object ? Thx
-
sourcedelica about 5 yearsYes.
datetime.min + delta
-
kleptog over 4 yearsHere you are just demonstrating subtracting complete datetime objects, not times-of-day as in the original question