繁体   English   中英

Python 使用 timedelta 数据的 .seconds 属性给出错误结果

[英]Python gives wrong result with .seconds attribute of timedelta data

>>>print(today - date, (today - date).seconds)

[1] 63 days, 8:45:34.250649 31534
                              ↑

这与正确的结果相去甚远。 31534 秒远小于 63 天。 为什么python给出错误的值?

你只请求seconds的的timedelta -你需要timedelta.totalseconds()

timedelta.seconds仅报告增量最后一天花费的所有秒数。

https://docs.python.org/3/library/datetime.html#datetime.timedelta.total_seconds

import datetime

d1 = datetime.datetime.now()

d2 = datetime.datetime.now()-datetime.timedelta(days=1.4)

delta = d1-d2

print(delta, delta.seconds, delta.total_seconds(), sep="\n")

输出:

1 day, 9:35:59.999997
34559  # (9 * 60 + 35 ) * 60 + 59 ca. 34559 - the full day is not part of ".seconds" 
120959.999997

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM