使用python中的datetime模块求取两个日期的间隔
from datetime import datetime
date1 = datetime.strptime('2018-05-29 23:59:00', '%Y-%m-%d %H:%M:%S')
date2 = datetime.strptime('2019-05-31 01:00:00', '%Y-%m-%d %H:%M:%S')
# 我们可以知道时间间隔是1年25小时1分钟
# 时间间隔的属性有 days,seconds,total_seconds()
interval_day = (date2-date1).days
interval_seconds = (date2-date1).seconds
interval = (date2-date1).total_seconds()
print(interval_day)
print(interval_seconds)
print(interval)
print(366*24*60*60+3660)
输出结果
366
3660
31626060.0
31626060
从结果上来看,我们可以知道:
days属性返回两个时间之间的天数差;
seconds属性返回两个时间之间的秒数差,小时,分钟,秒数的间隔之和,并以秒为单位表示
天数和秒数之和才是两时间之间的真实间隔。
total_seconds()方法:直接求得两时间之间的真实间隔,用秒表示。
本文介绍如何使用Python的datetime模块计算两个日期之间的间隔,包括天数、秒数和总秒数,通过实例演示了days、seconds和total_seconds()方法的使用。
8万+

被折叠的 条评论
为什么被折叠?



