datetime 计算时间差(小时)

2020-11-21  本文已影响0人  随时学丫

因为datetime计算时间差,只有 seconds, days,没有hours,于是,我就利用 seconds / 3600,来计算hours,但是出现了错误的结果

(new_time - old_time).seconds
(new_time - old_time).days

datetime计算hours案例

from datetime import datetime
def calc_hours(old):
    old_time = datetime.strptime(old, "%Y-%m-%d %H:%M:%S,%f")
    new_time = datetime.now()
    sec = (new_time - old_time).seconds
    return round(sec/3600, 3)

t = '2020-11-19 15:04:47,397'
print(calc_hours(t))

计算结果

old_time:  2020-11-19 15:04:47.397000
new_time:  2020-11-21 22:48:12.076836
7.723

对,你没有看错,是 7 小时,19 号和 21 号相差2天,结果有问题,然后我又算了下days的结果

from datetime import datetime
def calc_hours(old):
    old_time = datetime.strptime(old, "%Y-%m-%d %H:%M:%S,%f")
    new_time = datetime.now()
    days = (new_time - old_time).days
    return days

t = '2020-11-19 15:04:47,397'
print(calc_hours(t))

计算结果

old_time:  2020-11-19 15:04:47.397000
new_time:  2020-11-21 22:50:19.873813
2

天数是对的

后来,我又看了下秒数计算的结果,下午15点到晚上22点多,小时差不多就是 7.723,所以,这个秒数是计算的当天的小时数,而不是总的小时数

因此,想要计算总的小时数,需要把两个时间相加

from datetime import datetime
def calc_hours(old):
    old_time = datetime.strptime(old, "%Y-%m-%d %H:%M:%S,%f")
    new_time = datetime.now()
    days = (new_time - old_time).days
    sec = (new_time - old_time).seconds
    hours = days * 24 + round(sec/3600, 3)
    return hours
t = '2020-11-20 15:04:47,397'
print(calc_hours(t))

计算结果

old_time:  2020-11-19 15:04:47.397000
new_time:  2020-11-21 22:54:27.109447
days:  2
sec:  28179
55.827
上一篇下一篇

猜你喜欢

热点阅读