Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python TypeError adding time using timedelta

Tags:

python

I'm trying to add time. eventually I will create a function passing different times and I want to change the time. For some reason I can't make timedelta to do it.

this is my code:

time1 = datetime.time(9,0)
timedelta = datetime.timedelta(minutes=15)
time2 = time1 + timedelta

error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'

what should i change?

like image 349
user1871528 Avatar asked Sep 05 '25 19:09

user1871528


2 Answers

You can only add a timedelta to a datetime (as pointed out by Ben). What you can do, is make a datetime object with your time and then add the timedelta. This can then be turned back to and time object. The code to do this would look like this:

time1 = datetime.time(9,0)
timedelta = datetime.timedelta(minutes=15)
tmp_datetime = datetime.datetime.combine(datetime.date(1, 1, 1), time1)
time2 = (tmp_datetime + timedelta).time()
like image 88
Leon Avatar answered Sep 08 '25 09:09

Leon


time objects don't participate in arithmetic by design: there's no compelling answer to "what happens if the result overflows? Wrap around? Raise OverflowError?".

You can implement your own answer by combining the time object with a date to create a datetime, do the arithmetic, and then examine the result. For example, if you like "wrap around" behavior:

>>> time1 = datetime.time(9,0)
>>> timedelta = datetime.timedelta(minutes=15)
>>> time2 = (datetime.datetime.combine(datetime.date.today(), time1) +
        timedelta).time()
>>> time2
datetime.time(9, 15)

Or adding 1000 times your delta, to show the overflow behavior:

>>> time2 = (datetime.datetime.combine(datetime.date.today(), time1) +
        timedelta * 1000).time()
>>> time2
datetime.time(19, 0)
like image 31
Tim Peters Avatar answered Sep 08 '25 08:09

Tim Peters