seconds和total_seconds的区别

一 seconds和total_seconds的区别

共同点:都是计算两个时间点的时间差秒钟数

主要区别:

  • seconds只会计算时间点上的时间差的秒钟数,不能跨天计算时间差
  • total_seconds计算总的时间差的秒钟数,可以跨天计算
  • .seconds直接调,total_seconds() 要括号
  • 使用.seconds时,开始时间不能晚于结束时间,不然会按下一天的时间来计算时间差

1.1 计算同一天的数据

from datetime import datetime

start_time = datetime.fromisoformat('2023-07-17T00:00:00+08:00')
end_time = datetime.fromisoformat('2023-07-17T06:00:00+08:00')

next_hours = (end_time - start_time).seconds / 60  # 时间差
next_hours_total = (end_time - start_time).total_seconds() / 60  # 时间差

print(f'next_hours:{next_hours}, next_hours_total:{next_hours_total}')
"""输出结果: next_hours:360.0, next_hours_total:360.0"""

当计算同一天的时间差的时候,两个方法计算结果相同。

1.2 计算跨天的时间差

start_time = datetime.fromisoformat('2023-07-17T00:00:00+08:00')
end_time = datetime.fromisoformat('2023-07-18T06:00:00+08:00')

next_hours = (end_time - start_time).seconds / 60  # 时间差
next_hours_total = (end_time - start_time).total_seconds() / 60  # 时间差

print(f'next_hours:{next_hours}, next_hours_total:{next_hours_total}')
"""输出结果: next_hours:360.0, next_hours_total:1800.0"""

当跨天计算的时候,seconds只计算了 0点到6点的时差360分钟,没考虑相差的一天,而total_seconds考虑了相差的那一天的时长,所以总的为1800分钟。使用时主要考虑计算的时差是否会跨天计算,如果跨天的话计算时间差使用 total_seconds

1.3 开始时间晚于结束时间的情况

start_time = datetime.fromisoformat('2023-07-17T06:00:00+08:00')
end_time = datetime.fromisoformat('2023-07-17T00:00:00+08:00')

next_hours = (end_time - start_time).seconds / 60  # 时间差
next_hours_total = (end_time - start_time).total_seconds() / 60  # 时间差

print(f'next_hours:{next_hours}, next_hours_total:{next_hours_total}')
"""输出结果: next_hours:1080.0, next_hours_total:-360.0"""

当开始时间晚于结束时间的时候计算时间差的结果也会不同,seconds计算结果是正数,按下一天的这个时间点来算的时差,而total_seconds计算结果为正常理解的时差。

1.4 源码计算逻辑

timedelta 对象中的 total_seconds() 方法的实现。这个方法的主要作用是计算时间间隔对象中的总秒数。时间间隔对象包括几个部分:days(天数)、seconds(秒数)、microseconds(微秒数)。total_seconds() 方法会将这些部分合并成一个总秒数

def total_seconds(self):
    """Total seconds in the duration."""
    return ((self.days * 86400 + self.seconds) * 10 ** 6 +
            self.microseconds) / 10 ** 6

猜你喜欢

转载自blog.csdn.net/March_A/article/details/134114294