Format timedelta to string

后端 未结 28 1694
春和景丽
春和景丽 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:26

    One liner. Since timedeltas do not offer datetime's strftime, bring the timedelta back to a datetime, and use stftime.

    This can not only achieve the OP's requested format Hours:Minutes, now you can leverage the full formatting power of datetime's strftime, should your requirements change to another representation.

    import datetime
    td = datetime.timedelta(hours=2, minutes=10, seconds=5)
    print(td)
    print(datetime.datetime.strftime(datetime.datetime.strptime(str(td), "%H:%M:%S"), "%H:%M"))
    
    Output:
    2:10:05
    02:10
    

    This also solves the annoyance that timedeltas are formatted into strings as H:MM:SS rather than HH:MM:SS, which lead me to this problem, and the solution I've shared.

    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-11-22 04:28
    def td_format(td_object):
        seconds = int(td_object.total_seconds())
        periods = [
            ('year',        60*60*24*365),
            ('month',       60*60*24*30),
            ('day',         60*60*24),
            ('hour',        60*60),
            ('minute',      60),
            ('second',      1)
        ]
    
        strings=[]
        for period_name, period_seconds in periods:
            if seconds > period_seconds:
                period_value , seconds = divmod(seconds, period_seconds)
                has_s = 's' if period_value > 1 else ''
                strings.append("%s %s%s" % (period_value, period_name, has_s))
    
        return ", ".join(strings)
    
    0 讨论(0)
  • 2020-11-22 04:28

    A straight forward template filter for this problem. The built-in function int() never rounds up. F-Strings (i.e. f'') require python 3.6.

    @app_template_filter()
    def diffTime(end, start):
        diff = (end - start).total_seconds()
        d = int(diff / 86400)
        h = int((diff - (d * 86400)) / 3600)
        m = int((diff - (d * 86400 + h * 3600)) / 60)
        s = int((diff - (d * 86400 + h * 3600 + m *60)))
        if d > 0:
            fdiff = f'{d}d {h}h {m}m {s}s'
        elif h > 0:
            fdiff = f'{h}h {m}m {s}s'
        elif m > 0:
            fdiff = f'{m}m {s}s'
        else:
            fdiff = f'{s}s'
        return fdiff
    
    0 讨论(0)
提交回复
热议问题