我想以小时为单位计算时差,而不考虑日期。
例如,我希望22:00:00
和01:00:00
之间的差为3
。
到目前为止我得到的代码:
time1 = datetime.strptime("22:00:00", '%H:%M:%S')
time2 = datetime.strptime("01:00:00", '%H:%M:%S')
res = time1-time2
print(res)
我得到的输出:21:00:00
我想要的输出:3
答案 0 :(得分:2)
您不能直接从所得的timedelta
对象中提取小时数,因为它们将一天的几分之一秒保持不变,因此一种简单的解决方法是采用秒数并从那里计算小时数。
还要注意,您想将time1
减去time2
,否则您将得到21
小时:
(time2 - time1).seconds/3600
# 3