Format timedelta to string

后端 未结 28 1729
春和景丽
春和景丽 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条回答
  •  -上瘾入骨i
    2020-11-22 04:07

    Here's a function to stringify timedelta.total_seconds(). It works in python 2 and 3.

    def strf_interval(seconds):
        days, remainder = divmod(seconds, 86400)
        hours, remainder = divmod(remainder, 3600)
        minutes, seconds = divmod(remainder, 60)
        return '{} {} {} {}'.format(
                "" if int(days) == 0 else str(int(days)) + ' days',
                "" if int(hours) == 0 else str(int(hours)) + ' hours',
                "" if int(minutes) == 0 else str(int(minutes))  + ' mins',
                "" if int(seconds) == 0 else str(int(seconds))  + ' secs'
            )
    

    Example output:

    >>> print(strf_interval(1))
       1 secs
    >>> print(strf_interval(100))
      1 mins 40 secs
    >>> print(strf_interval(1000))
      16 mins 40 secs
    >>> print(strf_interval(10000))
     2 hours 46 mins 40 secs
    >>> print(strf_interval(100000))
    1 days 3 hours 46 mins 40 secs
    

提交回复
热议问题