【问题标题】:Python gives wrong result with .seconds attribute of timedelta dataPython 使用 timedelta 数据的 .seconds 属性给出错误结果
【发布时间】:2019-05-31 11:35:57
【问题描述】:
>>>print(today - date, (today - date).seconds)

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

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

【问题讨论】:

    标签: python python-3.x python-2.7 date datetime


    【解决方案1】:

    您只请求timedelta 中的seconds - 您需要the 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
    

    【讨论】:

      猜你喜欢
      • 2014-11-18
      • 2019-07-04
      • 1970-01-01
      • 2018-02-09
      • 2012-08-30
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多