Created
November 14, 2012 07:22
-
-
Save eagleon/4070791 to your computer and use it in GitHub Desktop.
人性化日期显示
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@app.template_filter('datetimeformat') | |
def timesince(dt, default="刚刚"): | |
""" | |
返回人性化,时间字符串。e.g.: | |
3 天前, 5小时前 etc. | |
""" | |
now = datetime.utcnow() | |
diff = now - dt | |
periods = ( | |
(diff.days / 365, "year"), | |
(diff.days / 30, "月"), | |
(diff.days / 7, "周"), | |
(diff.days, "天"), | |
(diff.seconds / 3600, "小时"), | |
(diff.seconds / 60, "分钟"), | |
(diff.seconds, "秒"), | |
) | |
flag=0 | |
for period, plural in periods: | |
flag+=1 | |
if period: | |
return default if flag == 7 and period<45 else "%d%s前" % (period, plural) | |
return default |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment