Format timedelta to string

后端 未结 28 2037
春和景丽
春和景丽 2020-11-22 03:57

I\'m having trouble formatting a datetime.timedelta object.

Here\'s what I\'m trying to do: I have a list of objects and one of the members of the cl

28条回答
  •  醉梦人生
    2020-11-22 04:27

    I had a similar problem with the output of overtime calculation at work. The value should always show up in HH:MM, even when it is greater than one day and the value can get negative. I combined some of the shown solutions and maybe someone else find this solution useful. I realized that if the timedelta value is negative most of the shown solutions with the divmod method doesn't work out of the box:

    def td2HHMMstr(td):
      '''Convert timedelta objects to a HH:MM string with (+/-) sign'''
      if td < datetime.timedelta(seconds=0):
        sign='-'
        td = -td
      else:
        sign = ''
      tdhours, rem = divmod(td.total_seconds(), 3600)
      tdminutes, rem = divmod(rem, 60)
      tdstr = '{}{:}:{:02d}'.format(sign, int(tdhours), int(tdminutes))
      return tdstr
    

    timedelta to HH:MM string:

    td2HHMMstr(datetime.timedelta(hours=1, minutes=45))
    '1:54'
    
    td2HHMMstr(datetime.timedelta(days=2, hours=3, minutes=2))
    '51:02'
    
    td2HHMMstr(datetime.timedelta(hours=-3, minutes=-2))
    '-3:02'
    
    td2HHMMstr(datetime.timedelta(days=-35, hours=-3, minutes=-2))
    '-843:02'
    

提交回复
热议问题