user1871528
user1871528

Reputation: 1775

python TypeError adding time using timedelta

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?

Upvotes: 4

Views: 4621

Answers (2)

Leon
Leon

Reputation: 3036

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()

Upvotes: 4

Tim Peters
Tim Peters

Reputation: 70582

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)

Upvotes: 1

Related Questions