Python add second to time object

Viewed 65

I need to add second to a string time using python datetime, I have following code, but got error

from datetime import datetime,timedelta

time = "13-15-12"
duration = 15
time_object = datetime.strptime(time, '%H-%M-%S').time()
time_object_end = time_object + timedelta(seconds=duration)

But got the error

time_object_end = time_object + timedelta(seconds=duration)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
1 Answers

You can only add timedeltas to datetimes. A pure time can't represent anything a clock display couldn't, so if your time was e.g. 23:55 and you add 15 minutes to it, you'd lose information about the day having changed.

Instead work with datetimes and only grab the time at the end:

>>> from datetime import datetime,timedelta
>>>
>>> time = "13-15-12"
>>> duration = 15
>>> time_object = datetime.strptime(time, '%H-%M-%S')
>>> time_object_end = time_object + timedelta(seconds=duration)
>>> time_object_end.time()
datetime.time(13, 15, 27)
>>>
Related