Format timedelta to string

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

    I have a function:

    def period(delta, pattern):
        d = {'d': delta.days}
        d['h'], rem = divmod(delta.seconds, 3600)
        d['m'], d['s'] = divmod(rem, 60)
        return pattern.format(**d)
    

    Examples:

    >>> td = timedelta(seconds=123456789)
    >>> period(td, "{d} days {h}:{m}:{s}")
    '1428 days 21:33:9'
    >>> period(td, "{h} hours, {m} minutes and {s} seconds, {d} days")
    '21 hours, 33 minutes and 9 seconds, 1428 days'
    

提交回复
热议问题