How can I format timedelta for display

后端 未结 6 1958
Happy的楠姐
Happy的楠姐 2020-12-20 13:13

My script calculate the difference in 2 time. Like this:

lasted = datetime.strptime(previous_time, FMT) - datetime.strptime(current_time, FMT)
6条回答
  •  悲哀的现实
    2020-12-20 13:35

    [insert shameless self-promotion disclamer here]

    You can use https://github.com/frnhr/django_timedeltatemplatefilter

    It's packaged as a tempalte filter for Django, so here is the important part, just plain Python:

    def format_timedelta(value, time_format="{days} days, {hours2}:{minutes2}:{seconds2}"):
    
        if hasattr(value, 'seconds'):
            seconds = value.seconds + value.days * 24 * 3600
        else:
            seconds = int(value)
    
        seconds_total = seconds
    
        minutes = int(floor(seconds / 60))
        minutes_total = minutes
        seconds -= minutes * 60
    
        hours = int(floor(minutes / 60))
        hours_total = hours
        minutes -= hours * 60
    
        days = int(floor(hours / 24))
        days_total = days
        hours -= days * 24
    
        years = int(floor(days / 365))
        years_total = years
        days -= years * 365
    
        return time_format.format(**{
            'seconds': seconds,
            'seconds2': str(seconds).zfill(2),
            'minutes': minutes,
            'minutes2': str(minutes).zfill(2),
            'hours': hours,
            'hours2': str(hours).zfill(2),
            'days': days,
            'years': years,
            'seconds_total': seconds_total,
            'minutes_total': minutes_total,
            'hours_total': hours_total,
            'days_total': days_total,
            'years_total': years_total,
        })
    

    Doesn't get more simple than that :) Still, check out the readme for a few examples.

    For your example:

    >>> format_timedelta(lasted, '{hours_total}:{minutes2}:{seconds2}')
    0:02:01
    

提交回复
热议问题