python – 两次之间的小时数?(不支持的操作数类型 – :’datetime.time’和’datetime.time’)

我试图通过浮动类型计算10:49到16:38之间的小时数.

import datetime
t1 = datetime.time(10,49,00)
t2 = datetime.time(16,38,00)
t = (t2 - t1).hours

最佳答案 你可以这样计算:

from datetime import datetime, timedelta

t1 = datetime.strptime("10:49:00", "%H:%M:%S")
t2 = datetime.strptime("16:38:00", "%H:%M:%S")
t = (t2 - t1)
print t.total_seconds() / 3600

print timedelta(days=0, seconds=t.seconds, microseconds=t.microseconds)
print ceil(t.total_seconds() / 3600)

输出:

5.81666666667
5:49:00
6.0

从timedelta得到一小时:

x = timedelta(days=0, seconds=t.seconds, microseconds=t.microseconds)
print x.seconds//3600

输出为5.

点赞