Search code examples
pythontimedelta

How to add/subract operation between two different times using timedelta?


So i'm trying know in what time of day the man will end running. When in last line of code, trying to use an operator addition this error is popping out. What i'm doing wrong?

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

import datetime
# first run, 1 mile

pace_minutes1 = 8
pace_seconds1 = 15
distance = 1  #1 mile
b = ((pace_minutes1 * 60) + pace_seconds1) * distance
print(b)

# second run, 3 mile
pace_minutes2 = 7
pace_seconds2 = 12
distance = 3  # 3 miles
a = ((pace_minutes2 * 60) + pace_seconds2) * distance
print(a)

# third run, 1 mile run
pace_minutes3 = 8
pace_seconds3 = 15
distance = 1 # 1 mile
c = ((pace_minutes3 * 60) + pace_seconds3) * distance
print(c)

x = (a + b + c)
print(x, "seconds")

time = datetime.timedelta(seconds=x) # converse value "x" seconds to time (h,m,s)
print("All running time will gonna take",time,"seconds") # total time spent running
start_time = datetime.time(6,52,0) # time from where he started running
print("The running started in",start_time)
end_time = (start_time + time) # time when he ended running
print(end_time)

Solution

  • You can only add the timedelta to a datetime.datetime object, not a datetime.time object (probably in order to avoid overflows).

    So simple fix, use start_time = datetime.datetime(2021, 04, 21, 6,52,0)