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

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

    Old question, but I personally like this approach most:

    import datetime
    import math
    
    def human_time(*args, **kwargs):
        secs  = float(datetime.timedelta(*args, **kwargs).total_seconds())
        units = [("day", 86400), ("hour", 3600), ("minute", 60), ("second", 1)]
        parts = []
        for unit, mul in units:
            if secs / mul >= 1 or mul == 1:
                if mul > 1:
                    n = int(math.floor(secs / mul))
                    secs -= n * mul
                else:
                    n = secs if secs != int(secs) else int(secs)
                parts.append("%s %s%s" % (n, unit, "" if n == 1 else "s"))
        return ", ".join(parts)
    
    human_time(seconds=3721)
    # -> "1 hour, 2 minutes, 1 second"
    

    If you want to separate the seconds part with an "and" do:

    "%s and %s" % tuple(human_time(seconds=3721).rsplit(", ", 1))
    # -> "1 hour, 2 minutes and 1 second"
    

提交回复
热议问题