【问题标题】:How to get total hours and minutes for timedelta in Python如何在 Python 中获取 timedelta 的总小时数和分钟数
【发布时间】:2015-01-12 23:53:49
【问题描述】:

如何将大于 24 小时的 timedelta 返回或转换为包含总小时和分钟(例如 26:30)而不是“1 天,2:30”的对象?

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    您可以使用total_seconds() 来计算秒数。然后可以将其转换为分钟或小时:

    >>> datetime.timedelta(days=3).total_seconds()
    259200.0
    

    【讨论】:

    • 正确答案,但添加简单的 //60%60 使用将其变成(小时、天)对会很有帮助!
    • 谢谢。我结束了使用在这里找到的答案:stackoverflow.com/questions/14190045/…
    【解决方案2】:

    使用timedelta.total_seconds()完成Visser的回答:

    import datetime
    duration = datetime.timedelta(days = 2, hours = 4, minutes = 15)
    

    一旦我们得到一个timedelta 对象:

    totsec = duration.total_seconds()
    h = totsec//3600
    m = (totsec%3600) // 60
    sec =(totsec%3600)%60 #just for reference
    print "%d:%d" %(h,m)
    
    Out: 52:15
    

    【讨论】:

      【解决方案3】:
      offset_seconds = timedelta.total_seconds()
      
      if offset_seconds < 0:
          sign = "-"
      else:
          sign = "+"
      
      # we will prepend the sign while formatting
      if offset_seconds < 0:
          offset_seconds *= -1
      
      offset_hours = offset_seconds / 3600.0
      offset_minutes = (offset_hours % 1) * 60
      
      offset = "{:02d}:{:02d}".format(int(offset_hours), int(offset_minutes))
      offset = sign + offset
      

      【讨论】:

        猜你喜欢
        • 2015-09-25
        • 1970-01-01
        • 2017-03-17
        • 2023-04-05
        • 2020-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多