4

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?

3
  • timedelta objects can only be added to datetime.datetime objects, not datetime.time objects. Commented Jun 12, 2016 at 21:36
  • I think you need a datetime.datetime object in order to add a timedelta Commented Jun 12, 2016 at 21:36
  • Okay so how can I change a datetime.time object instead of manually define it every time? Commented Jun 12, 2016 at 21:39

2 Answers 2

4

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.