【问题标题】:How do I check the difference, in seconds, between two dates?如何检查两个日期之间的差异(以秒为单位)?
【发布时间】:2011-05-20 17:38:32
【问题描述】:

必须有一种更简单的方法来做到这一点。我有想要经常刷新的对象,所以我想记录它们的创建时间,检查当前时间戳,并在必要时刷新。

datetime.datetime 被证明是困难的,我不想深入 ctime 库。这种事情有什么更容易的吗?

【问题讨论】:

    标签: python time datediff


    【解决方案1】:

    如果您想计算两个已知日期之间的差异,请像这样使用total_seconds

    import datetime as dt
    
    a = dt.datetime(2013,12,30,23,59,59)
    b = dt.datetime(2013,12,31,23,59,59)
    
    (b-a).total_seconds()
    

    86400.0

    #note that seconds doesn't give you what you want:
    (b-a).seconds
    

    0

    【讨论】:

    • “注释”是人们最容易错过的部分。我希望我能再投赞成票。
    • 有时我注意到它给出了一个看似...不正确的结果。 59.800 秒的瞬间差异。因此,对于较小的操作,例如秒、毫秒或微秒的差异,可以使用 (b-a).microseconds 然后将其除以得到秒 (1000000) 或毫秒 (1000)
    • 它的值似乎总是正数,即使 a 和 b 交换了
    • 这很有帮助。但是为什么python总是给(b-a).seconds给出错误的答案呢?
    • @enchance 这是因为 (b-a).seconds 仅表示差异的秒数部分。还有 (b-a).minutes , (b-a).hours, ...
    【解决方案2】:
    import time  
    current = time.time()
    
    ...job...
    end = time.time()
    diff = end - current
    

    这对你有用吗?

    【讨论】:

    • +1;我们并不真正关心任何一次调用的日期——我们关心的是经过的时间。所以只需使用原始时间戳,如图所示。
    【解决方案3】:
    >>> from datetime import datetime
    
    >>>  a = datetime.now()
    
    # wait a bit 
    >>> b = datetime.now()
    
    >>> d = b - a # yields a timedelta object
    >>> d.seconds
    7
    

    (7 将是您在上面等待的时间)

    我发现 datetime.datetime 相当有用,所以如果您遇到复杂或尴尬的情况,请告诉我们。

    编辑:感谢@WoLpH 指出,人们不一定总是希望如此频繁地刷新,以至于日期时间会很接近。通过考虑增量中的天数,您可以处理更长的时间戳差异:

    >>> a = datetime(2010, 12, 5)
    >>> b = datetime(2010, 12, 7)
    >>> d = b - a
    >>> d.seconds
    0
    >>> d.days
    2
    >>> d.seconds + d.days * 86400
    172800
    

    【讨论】:

    • 如果您改为返回d.seconds + d.days * 86400,则多天都是正确的;)
    • 请注意,在一般情况下,这是不正确的。考虑a - b 的情况,其中a之前 b(即,结果将为负):(a - b).seconds == 86282a - b == datetime.timedelta(-1, 86276, 627665)。我相信正确的方法是使用timedelta.total_seconds()...但那只是py2.7+。
    • 确实,答案不正确,应该反映@DavidWolever 的评论。正确答案是:使用timedelta.total_seconds()。相应地被否决了。
    • 赞成 Python 2.6 答案。 total_seconds() 是 2.7+ 的功能。
    • @JoeHolloway 我猜这在 Python 2.6 中也不能正常工作。
    【解决方案4】:

    我们在 Python 2.7 中有函数 total_seconds() 请参阅下面的 python 2.6 代码

    import datetime
    import time  
    
    def diffdates(d1, d2):
        #Date format: %Y-%m-%d %H:%M:%S
        return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
                   time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))
    
    d1 = datetime.now()
    d2 = datetime.now() + timedelta(days=1)
    diff = diffdates(d1, d2)
    

    【讨论】:

      【解决方案5】:

      这是为我工作的那个。

      from datetime import datetime
      
      date_format = "%H:%M:%S"
      
      # You could also pass datetime.time object in this part and convert it to string.
      time_start = str('09:00:00') 
      time_end = str('18:00:00')
      
      # Then get the difference here.    
      diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)
      
      # Get the time in hours i.e. 9.60, 8.5
      result = diff.seconds / 3600;
      

      希望这会有所帮助!

      【讨论】:

        【解决方案6】:

        另一种方法是使用时间戳值:

        end_time.timestamp() - start_time.timestamp()
        

        【讨论】:

          【解决方案7】:

          通过阅读源码得出一个结论:.seconds无法获取时差:

          @property
          def seconds(self):
              """seconds"""
              return self._seconds
          
          # in the `__new__`, you can find the `seconds` is modulo by the total number of seconds in a day
          def __new__(cls, days=0, seconds=0, microseconds=0,
                      milliseconds=0, minutes=0, hours=0, weeks=0):
              seconds += minutes*60 + hours*3600
              # ...
              if isinstance(microseconds, float):
                  microseconds = round(microseconds + usdouble)
                  seconds, microseconds = divmod(microseconds, 1000000)
                  # ! ?
                  days, seconds = divmod(seconds, 24*3600)
                  d += days
                  s += seconds
              else:
                  microseconds = int(microseconds)
                  seconds, microseconds = divmod(microseconds, 1000000)
                  # ! ?
                  days, seconds = divmod(seconds, 24*3600)
                  d += days
                  s += seconds
                  microseconds = round(microseconds + usdouble)
              # ...
          

          total_seconds 可以得到两个时间之间的准确差异

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

          总结:

          from datetime import datetime
          dt1 = datetime.now()
          dt2 = datetime.now()
          
          print((dt2 - dt1).total_seconds())
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-04-27
            • 1970-01-01
            • 2012-09-13
            • 1970-01-01
            • 1970-01-01
            • 2012-05-16
            • 1970-01-01
            • 2012-12-03
            相关资源
            最近更新 更多