自定义时间过滤器
无纤尘
自定义时间过滤器
题目:用户发一个帖子,要求记录用户发帖时间距当前的时间戳。
时间戳不超过60s时,返回“刚刚”
时间戳超过60s,且不超过1h,返回“几分钟前”
时间戳超过1h,且不超过1天,返回“几小时前”
时间戳超过1天,且不超过30天,返回“几天前”
时间戳超过30天,,返回发布时间。
解答:
首先导入datetime
from datetime import datetime
编写python代码
@app.route('/')
def hello():
context = {
'creat_time':datetime(2020,12,2,11,39,00)
}
return render_template('index.html',**context)
@app.template_filter('handle_time')
def handle_time(time):
if isinstance(time,datetime):
now = datetime.now()
timestamp = (now - time).total_seconds()
if timestamp <= 60:
return u'刚刚'
elif timestamp >= 60 and timestamp<= 60*60:
minutes = timestamp/60
return u'%s分钟前' % minutes
elif timestamp >= 60*60 and timestamp<= 60*60*24:
minutes = timestamp/(60*60)
return u'%s小时前' % minutes
elif timestamp >= 60*60*24 and timestamp<= 60*60*24*30:
minutes = timestamp/(60*60*24)
return u'%s天前' % minutes
else:
return time.strftime('%Y/%m/%d %H:%M')
else:
return time
编写html代码
<h1>发布时间:{{creat_time|handle_time}}</h1>
版权协议须知!
本篇文章来源于 岳岳 ,如本文章侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意
1583 0 2020-12-02