python中添加了两个datetime.datetime.strptime()。time()对象 [英] Addition of two datetime.datetime.strptime().time() objects in python
问题描述
我想以'HH:MM:SS'格式添加两个时间值t1和t2。
I want to add two time values t1 and t2 in format 'HH:MM:SS'.
t1 ='12:00:00'
t2='02:00:00'
t1 + t2
应该为 14:00:00
I尝试了 t1 + t2
。但是作为 t1
& t2
是字符串格式,输出为串联 12:00:00 02:00:00
。
I tried t1+t2
. But as t1
& t2
are im string format the output was concatenation 12:00:00 02:00:00
.
所以我尝试在datetime.datetime.strptime()。time()对象中进行转换,例如
So I tried to convert in datetime.datetime.strptime().time() object like
t1 = datetime.datetime.strptime('12:00:00', '%H:%M:%S').time()
t2 = datetime.datetime.strptime('02:00:00', '%H:%M:%S').time()
但是给出错误
TypeError:+不支持的操作数类型: datetime.time和 datetime.time
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'
我该如何使用它?
推荐答案
您不能直接添加两个 time()
变量。这是因为这些时间变量不是持续时间。他们是一天中的时间。但是,您可以通过从时间变量中减去午夜来将时间变量转换为持续时间。
You can not directly add two time()
variables. This is due to the fact that these time variables are not durations. They are the time of day. You can however turn a time variable into a duration by subtracting midnight from the time variable.
测试代码:
import datetime as dt
t1 = dt.datetime.strptime('12:00:00', '%H:%M:%S')
t2 = dt.datetime.strptime('02:00:00', '%H:%M:%S')
time_zero = dt.datetime.strptime('00:00:00', '%H:%M:%S')
print((t1 - time_zero + t2).time())
结果:
14:00:00
这篇关于python中添加了两个datetime.datetime.strptime()。time()对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!