python计算时间差之seconds()函数和total_seconds()函数的区别

前言

1、在python中经常会用到计算两个时间差,两个日期类型进行相减可以获取到时间差。

2、 seconds  函数获取的是仅仅是时间差的秒数,忽略微秒数,忽略天数。

3、 seconds 函数是获取时间部分的差值,而 total_seconds() 函数是获取两个时间之间的总差值。

t1 = datetime.datetime.strptime("2017-9-06 10:30:00", "%Y-%m-%d %H:%M:%S")
t2 = datetime.datetime.strptime("2017-9-08 12:30:00", "%Y-%m-%d %H:%M:%S")
td = (t2 - t1)
total_seconds() = (td.microseconds+ (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

实例

实例1:

复制代码
import datetime

# 比较的两个时间具有相同的年数、月数、天数(仅仅需要获取时间差的秒数)
t1 = datetime.datetime.strptime("2017-9-06 10:30:00", "%Y-%m-%d %H:%M:%S")
print(t1, type(t1))  # 2017-09-06 10:30:00 <class 'datetime.datetime'>
t2 = datetime.datetime.strptime("2017-9-06 12:30:00", "%Y-%m-%d %H:%M:%S")
print(t2, type(t2))  # 2017-09-06 12:30:00 <class 'datetime.datetime'>

interval_time = (t2 - t1).seconds  # 输出的结果:7200
total_interval_time = (t2 - t1).total_seconds()  # 输出结果是: 7200.0
print(interval_time)
print(total_interval_time)

# 比较的两个时间天数不相同(需要获取两个时间的所有时间差)
t1 = datetime.datetime.strptime("2017-9-06 10:30:00", "%Y-%m-%d %H:%M:%S")
t2 = datetime.datetime.strptime("2017-9-08 12:30:00", "%Y-%m-%d %H:%M:%S")
interval_time = (t2 - t1).seconds  # 输入的结果:7200
total_interval_time = (t2 - t1).total_seconds()  # 输出结果是: 180000.0
print(interval_time)
print(total_interval_time)

td = (t2 - t1)
print('td:', td)  # 2 days, 2:00:00(两个时间相差两天零两个小时)
print((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 6)  # 180000.0
复制代码

实例2:

复制代码
import datetime

# 日期相同,时间不同
time_1 = '2021-09-17 08:45:56'
time_2 = '2021-09-17 08:30:00'

time_1_format = datetime.datetime.strptime(time_1, "%Y-%m-%d %H:%M:%S")  # 2021-09-17 08:45:56
time_2_format = datetime.datetime.strptime(time_2, "%Y-%m-%d %H:%M:%S")  # 2021-09-17 08:30:00

print((time_1_format - time_2_format).seconds)  # 956
print((time_1_format - time_2_format).total_seconds())  # 输出:956.0

print((time_2_format - time_1_format).seconds)  # -956.0
print((time_2_format - time_1_format).total_seconds())  # -85444.0(结果不对)

# 日期不同,时间不同
time_1 = '2021-09-16 08:45:56'
time_2 = '2021-09-17 08:30:00'

time_1_format = datetime.datetime.strptime(time_1, "%Y-%m-%d %H:%M:%S")  # 2021-09-16 08:45:56
time_2_format = datetime.datetime.strptime(time_2, "%Y-%m-%d %H:%M:%S")  # 2021-09-17 08:30:00

print((time_1_format - time_2_format).total_seconds())  # -85444.0(正确结果:将日期也相减再加上时分秒的相减最终得出结果)
print((time_1_format - time_2_format).seconds)  # 956(只输出了时分秒的时间差)
复制代码

 

posted @   习久性成  阅读(2660)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
历史上的今天:
2021-05-18 python操作mysql之pymysql
2021-05-18 python装饰器详解
2021-05-18 深刻理解Python中的元类(metaclass)以及元类实现单例模式
点击右上角即可分享
微信分享提示