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

后端 未结 7 1008
無奈伤痛
無奈伤痛 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 19:59

    A little improvement over @Schnouki's solution with a single line list comprehension. Also displays the plural in case of plural entities (like hours)

    Import relativedelta

    >>> from dateutil.relativedelta import relativedelta
    

    A lambda function

    >>> attrs = ['years', 'months', 'days', 'hours', 'minutes', 'seconds']
    >>> human_readable = lambda delta: ['%d %s' % (getattr(delta, attr), attr if getattr(delta, attr) > 1 else attr[:-1]) 
    ...     for attr in attrs if getattr(delta, attr)]
    

    Example usage:

    >>> human_readable(relativedelta(minutes=125))
    ['2 hours', '5 minutes']
    >>> human_readable(relativedelta(hours=(24 * 365) + 1))
    ['365 days', '1 hour']
    

提交回复
热议问题