User-friendly time format in Python?

后端 未结 14 1489
[愿得一人]
[愿得一人] 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:55

    I have written a detailed blog post for the solution on http://sunilarora.org/17329071 I am posting a quick snippet here as well.

    from datetime import datetime
    from dateutil.relativedelta import relativedelta
    
    def get_fancy_time(d, display_full_version = False):
        """Returns a user friendly date format
        d: some datetime instace in the past
        display_second_unit: True/False
        """
        #some helpers lambda's
        plural = lambda x: 's' if x > 1 else ''
        singular = lambda x: x[:-1]
        #convert pluran (years) --> to singular (year)
        display_unit = lambda unit, name: '%s %s%s'%(unit, name, plural(unit)) if unit > 0 else ''
    
        #time units we are interested in descending order of significance
        tm_units = ['years', 'months', 'days', 'hours', 'minutes', 'seconds']
    
        rdelta = relativedelta(datetime.utcnow(), d) #capture the date difference
        for idx, tm_unit in enumerate(tm_units):
            first_unit_val = getattr(rdelta, tm_unit)
            if first_unit_val > 0:
                primary_unit = display_unit(first_unit_val, singular(tm_unit))
                if display_full_version and idx < len(tm_units)-1:
                    next_unit = tm_units[idx + 1]
                    second_unit_val = getattr(rdelta, next_unit)
                    if second_unit_val > 0:
                        secondary_unit = display_unit(second_unit_val, singular(next_unit))
                        return primary_unit + ', '  + secondary_unit
                return primary_unit
        return None
    

提交回复
热议问题