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

后端 未结 7 974
無奈伤痛
無奈伤痛 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:13

    I had that exact same problem earlier today and I couldn't find anything in the standard libraries that I could use, so this is what I wrote:

    humanize_time.py

        #!/usr/bin/env python
    
        INTERVALS = [1, 60, 3600, 86400, 604800, 2419200, 29030400]
        NAMES = [('second', 'seconds'),
                 ('minute', 'minutes'),
                 ('hour', 'hours'),
                 ('day', 'days'),
                 ('week', 'weeks'),
                 ('month', 'months'),
                 ('year', 'years')]
    
        def humanize_time(amount, units):
        """
        Divide `amount` in time periods.
        Useful for making time intervals more human readable.
    
        >>> humanize_time(173, 'hours')
        [(1, 'week'), (5, 'hours')]
        >>> humanize_time(17313, 'seconds')
        [(4, 'hours'), (48, 'minutes'), (33, 'seconds')]
        >>> humanize_time(90, 'weeks')
        [(1, 'year'), (10, 'months'), (2, 'weeks')]
        >>> humanize_time(42, 'months')
        [(3, 'years'), (6, 'months')]
        >>> humanize_time(500, 'days')
        [(1, 'year'), (5, 'months'), (3, 'weeks'), (3, 'days')]
        """
           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
    
        if __name__ == "__main__":
            import doctest
            doctest.testmod()
    

    You can use dateutil.relativedelta() to calculate the accurate time delta and humanize it with this script.

    0 讨论(0)
提交回复
热议问题