Cod*_*ezk 3 python datetime timedelta python-3.x
我需要使用 python datetime 将秒添加到字符串时间,我有以下代码,但出现错误
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)
Run Code Online (Sandbox Code Playgroud)
但得到了错误
time_object_end = time_object + timedelta(seconds=duration)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
Run Code Online (Sandbox Code Playgroud)
您只能将时间增量添加到日期时间。一个纯time不能代表时钟显示不能代表的任何东西,所以如果你的时间是例如 23:55 并且你增加了 15 分钟,你会丢失关于日期已经改变的信息。
而是使用日期时间,只在最后获取时间:
>>> 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)
>>>
Run Code Online (Sandbox Code Playgroud)