Format timedelta to string

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

提交回复
热议问题