How can I produce a human readable difference when subtracting two UNIX timestamps using Python?

后端 未结 7 1010
無奈伤痛
無奈伤痛 2020-12-23 19:39

This question is similar to this question about subtracting dates with Python, but not identical. I\'m not dealing with strings, I have to figure out the difference between

7条回答
  •  再見小時候
    2020-12-23 20:02

    def humanize_time(amount, units = 'seconds'):    
    
        def process_time(amount, units):
    
            INTERVALS = [   1, 60, 
                            60*60, 
                            60*60*24, 
                            60*60*24*7, 
                            60*60*24*7*4, 
                            60*60*24*7*4*12, 
                            60*60*24*7*4*12*100,
                            60*60*24*7*4*12*100*10]
            NAMES = [('second', 'seconds'),
                     ('minute', 'minutes'),
                     ('hour', 'hours'),
                     ('day', 'days'),
                     ('week', 'weeks'),
                     ('month', 'months'),
                     ('year', 'years'),
                     ('century', 'centuries'),
                     ('millennium', 'millennia')]
    
            result = []
    
            unit = map(lambda a: a[1], NAMES).index(units)
            # Convert to seconds
            amount = amount * INTERVALS[unit]
    
            for i in range(len(NAMES)-1, -1, -1):
                a = amount // INTERVALS[i]
                if a > 0: 
                    result.append( (a, NAMES[i][1 % a]) )
                    amount -= a * INTERVALS[i]
    
            return result
    
        rd = process_time(int(amount), units)
        cont = 0
        for u in rd:
            if u[0] > 0:
                cont += 1
    
        buf = ''
        i = 0
        for u in rd:
            if u[0] > 0:
                buf += "%d %s" % (u[0], u[1])
                cont -= 1
    
            if i < (len(rd)-1):
                if cont > 1:
                    buf += ", "
                else:
                    buf += " and "
    
            i += 1
    
        return buf
    

    Example of use:

    >>> print humanize_time(234567890 - 123456789)
    3 years, 9 months, 3 weeks, 5 days, 11 minutes and 41 seconds
    >>> humanize_time(9, 'weeks')
    2 months and 1 week
    

    Advantage (You don't need third parties!).

    Improved from "Liudmil Mitev" algorithm. (Thanks!)

提交回复
热议问题