User-friendly time format in Python?

后端 未结 14 1456
[愿得一人]
[愿得一人] 2020-12-12 10:06

Python: I need to show file modification times in the \"1 day ago\", \"two hours ago\", format.

Is there something ready to do that? It should be in English.

14条回答
  •  时光说笑
    2020-12-12 10:57

    The answer Jed Smith linked to is good, and I used it for a year or so, but I think it could be improved in a few ways:

    • It's nice to be able to define each time unit in terms of the preceding unit, instead of having "magic" constants like 3600, 86400, etc. sprinkled throughout the code.
    • After much use, I find I don't want to go to the next unit quite so eagerly. Example: both 7 days and 13 days will show as "1 week"; I'd rather see "7 days" or "13 days" instead.

    Here's what I came up with:

    def PrettyRelativeTime(time_diff_secs):
        # Each tuple in the sequence gives the name of a unit, and the number of
        # previous units which go into it.
        weeks_per_month = 365.242 / 12 / 7
        intervals = [('minute', 60), ('hour', 60), ('day', 24), ('week', 7),
                     ('month', weeks_per_month), ('year', 12)]
    
        unit, number = 'second', abs(time_diff_secs)
        for new_unit, ratio in intervals:
            new_number = float(number) / ratio
            # If the new number is too small, don't go to the next unit.
            if new_number < 2:
                break
            unit, number = new_unit, new_number
        shown_num = int(number)
        return '{} {}'.format(shown_num, unit + ('' if shown_num == 1 else 's'))
    

    Notice how every tuple in intervals is easy to interpret and check: a 'minute' is 60 seconds; an 'hour' is 60 minutes; etc. The only fudge is setting weeks_per_month to its average value; given the application, that should be fine. (And note that it's clear at a glance that the last three constants multiply out to 365.242, the number of days per year.)

    One downside to my function is that it doesn't do anything outside the "## units" pattern: "Yesterday", "just now", etc. are right out. Then again, the original poster didn't ask for these fancy terms, so I prefer my function for its succinctness and the readability of its numerical constants. :)

提交回复
热议问题