用户友好的时间格式在Python?

Python:我需要在“1天前”,“2小时前”格式中显示文件修改时间。

有没有准备好这样做? 它应该是英文的。

该代码最初发布在博客文章“Python Pretty Datefunction”( http://evaisse.com/post/93417709/python-pretty-date-function

它在这里转载,因为博客帐户已被暂停,页面不再可用。

def pretty_date(time=False): """ Get a datetime object or a int() Epoch timestamp and return a pretty string like 'an hour ago', 'Yesterday', '3 months ago', 'just now', etc """ from datetime import datetime now = datetime.now() if type(time) is int: diff = now - datetime.fromtimestamp(time) elif isinstance(time,datetime): diff = now - time elif not time: diff = now - now second_diff = diff.seconds day_diff = diff.days if day_diff < 0: return '' if day_diff == 0: if second_diff < 10: return "just now" if second_diff < 60: return str(second_diff) + " seconds ago" if second_diff < 120: return "a minute ago" if second_diff < 3600: return str(second_diff / 60) + " minutes ago" if second_diff < 7200: return "an hour ago" if second_diff < 86400: return str(second_diff / 3600) + " hours ago" if day_diff == 1: return "Yesterday" if day_diff < 7: return str(day_diff) + " days ago" if day_diff < 31: return str(day_diff / 7) + " weeks ago" if day_diff < 365: return str(day_diff / 30) + " months ago" return str(day_diff / 365) + " years ago" 

如果你碰巧使用的是Django ,那么1.4版本中的新function就是naturaltime模板filter。

要使用它,首先将'django.contrib.humanize'添加到settings.py中的INSTALLED_APPS设置中,并将{% load humanize %}到您使用filter的模板中。

然后,在你的模板中,如果你有一个date时间variablesmy_date ,你可以使用{{ my_date|naturaltime }}来打印它与当前的距离,它会像4 minutes ago那样渲染。

Django 1.4中的其他新东西

django.contrib.humanize集合中naturaltime和其他filter的文档。

在寻找与处理未来date的额外要求相同的东西,我发现这个: http : //pypi.python.org/pypi/py-pretty/1

示例代码(来自网站):

 from datetime import datetime, timedelta now = datetime.now() hrago = now - timedelta(hours=1) yesterday = now - timedelta(days=1) tomorrow = now + timedelta(days=1) dayafter = now + timedelta(days=2) import pretty print pretty.date(now) # 'now' print pretty.date(hrago) # 'an hour ago' print pretty.date(hrago, short=True) # '1h ago' print pretty.date(hrago, asdays=True) # 'today' print pretty.date(yesterday, short=True) # 'yest' print pretty.date(tomorrow) # 'tomorrow' 

前面的包提供了这个。 在datetime对象上调用human来获取人类可读的差异描述。

 from ago import human from datetime import datetime from datetime import timedelta ts = datetime.now() - timedelta(days=1, hours=5) print(human(ts)) # 1 day, 5 hours ago print(human(ts, precision=1)) # 1 day ago 

杰德史密斯所说的答案是好的,我用了一年左右的时间,但是我认为可以通过几个方面来改进:

  • 能够按照前面的单位来定义每个时间单位,而不是像整个代码中的“魔术”常量(如3600,86400等)一样。
  • 经过多次使用,我发现我不想非常热切地去下一个单位。 例如:7天和13天都会显示为“1周”; 我宁可看“7天”或“13天”。

以下是我想到的:

 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')) 

请注意, intervals每个元组是如何易于解释和检查的: 'minute'60秒; 'hour'60分钟; 等等。唯一的方法是将weeks_per_month设置为平均值; 考虑到应用程序,这应该是好的。 (注意一眼就可以看出,最后三个常数乘以每年的天数365.242)。

我的function的一个缺点就是它没有在“##单位”模式之外做任何事情:“昨天”,“刚才”等都是正确的。 再一次,原始的海报没有要求这些奇特的术语,所以我更喜欢我的function,因为它的简洁性和数字常数的可读性。 🙂

你也可以用箭头包做

从github页面 :

 >>> import arrow >>> utc = arrow.utcnow() >>> utc = utc.replace(hours=-1) >>> local.humanize() 'an hour ago' 

有人性humanize包装 :

 >>> from datetime import datetime, timedelta >>> import humanize # $ pip install humanize >>> humanize.naturaltime(datetime.now() - timedelta(days=1)) 'a day ago' >>> humanize.naturaltime(datetime.now() - timedelta(hours=2)) '2 hours ago' 

它支持本地化l10n ,国际化i18n :

 >>> _ = humanize.i18n.activate('ru_RU') >>> print humanize.naturaltime(datetime.now() - timedelta(days=1)) день назад >>> print humanize.naturaltime(datetime.now() - timedelta(hours=2)) 2 часа назад 

我在http://sunilarora.org/17329071上写了一个关于解决scheme的详细博客文章。我在这里也发布了一个简短的代码片段。;

 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 

这是@sunil职位的要点

 >>> from datetime import datetime >>> from dateutil.relativedelta import relativedelta >>> then = datetime(2003, 9, 17, 20, 54, 47, 282310) >>> relativedelta(then, datetime.now()) relativedelta(years=-11, months=-3, days=-9, hours=-18, minutes=-17, seconds=-8, microseconds=+912664) 

与tzinfo一起使用datetime对象:

 def time_elapsed(etime): # need to add tzinfo to datetime.utcnow now = datetime.datetime.utcnow().replace(tzinfo=etime.tzinfo) opened_for = (now - etime).total_seconds() names = ["seconds","minutes","hours","days","weeks","months"] modulos = [ 1,60,3600,3600*24,3600*24*7,3660*24*30] values = [] for m in modulos[::-1]: values.append(int(opened_for / m)) opened_for -= values[-1]*m pretty = [] for i,nm in enumerate(names[::-1]): if values[i]!=0: pretty.append("%i %s" % (values[i],nm)) return " ".join(pretty) 

你可以从下面的链接下载并安装。 它应该对你更有帮助。 它一直提供用户友好的信息,从二年到一年。

它testing良好。

https://github.com/nareshchaudhary37/timestamp_content

下面的步骤安装到您的虚拟环境。

 git clone https://github.com/nareshchaudhary37/timestamp_content cd timestamp-content python setup.py