仅考虑小时数即可计算时差

时间:2019-05-21 19:25:28

标签: python

我想以小时为单位计算时差,而不考虑日期。

例如,我希望22:00:0001: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

1 个答案:

答案 0 :(得分:2)

您不能直接从所得的timedelta对象中提取小时数,因为它们将一天的几分之一秒保持不变,因此一种简单的解决方法是采用秒数并从那里计算小时数。

还要注意,您想将time1减去time2,否则您将得到21小时:

(time2 - time1).seconds/3600
# 3