在开发过程中,避免不了有时间计算的需求,两个datetime类型相减可获取时间差,使用seconds方法可将时间差转换成秒,但是也存在一定的问题,当减数大于被减数时,使用seconds方法得出的计算结果就不准确了,比如:

import datetime
c = datetime.datetime(2024, 4, 19, 8, 45, 15)
d = datetime.datetime(2024, 4, 19, 8, 30, 45)
print("seconds", (d - c).seconds)  # 输出结果:85530

为什么会得出此结果,是因为seconds方法是自动忽略日期的,只会计算时间,当然也有相关的解决方案,total_seconds()函数可以解决该问题

print("total_seconds", (d - c).total_seconds())  # 输出结果:-870.0

输出结果是float类型,如果需要整数,需要手动转换一下

打赏

发表评论

邮箱地址不会被公开。 必填项已用*标注