fly*_*ire 61 python formatting time datetime date
Python:我需要在"1天前","两小时前"格式中显示文件修改时间.
有什么准备好的吗?它应该是英文的.
Jed*_*ith 112
该代码最初发布在博客文章"Python Pretty Date function"(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"
Run Code Online (Sandbox Code Playgroud)
plo*_*man 30
如果你碰巧使用Django,那么版本1.4中的新功能就是naturaltime
模板过滤器.
要使用它,请先在settings.py中添加'django.contrib.humanize'
到您INSTALLED_APPS
的设置,然后添加到您{% load humanize %}
正在使用过滤器的模板中.
然后,在你的模板中,如果你有一个日期时间变量my_date
,你可以通过使用来打印它与现在的距离{{ my_date|naturaltime }}
,它将被渲染为类似的东西4 minutes ago
.
集合naturaltime
中的文档和其他过滤器django.contrib.humanize
.
Kar*_*rim 14
在寻找处理未来日期的额外要求时,我找到了这个: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'
Run Code Online (Sandbox Code Playgroud)
>>> 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'
Run Code Online (Sandbox Code Playgroud)
>>> _ = humanize.i18n.activate('ru_RU')
>>> print humanize.naturaltime(datetime.now() - timedelta(days=1))
???? ?????
>>> print humanize.naturaltime(datetime.now() - timedelta(hours=2))
2 ???? ?????
Run Code Online (Sandbox Code Playgroud)
您也可以使用箭头包来做到这一点
来自github页面:
Run Code Online (Sandbox Code Playgroud)>>> import arrow >>> utc = arrow.utcnow() >>> utc = utc.replace(hours=-1) >>> local.humanize() 'an hour ago'
Jed Smith与之相关的答案是好的,我使用了一年左右,但我认为可以通过以下几种方式改进:
这是我想出的:
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'))
Run Code Online (Sandbox Code Playgroud)
注意每个元组intervals
是如何易于解释和检查的:a 'minute'
是60
秒; 一个'hour'
是60
分钟; 唯一的软糖是设定weeks_per_month
其平均值; 鉴于申请,这应该没问题.(请注意,一目了然,最后三个常数乘以365.242,即每年的天数.)
我的功能的一个缺点是它不会在"## units"模式之外做任何事情:"昨天","刚才",等等.然后,原始的海报并没有要求这些花哨的术语,所以我更喜欢我的功能,因为它的简洁性和数字常数的可读性.:)