#自定义过滤器实战之评论时间记录 实际效果 该评论来自:5分钟之前 from datetime import datetime # register.filter(‘greet’,greet)这一句和下面是一样的功能,注册过滤器 如果filter没有传入参数的话将会使用这个函数的名字作为过滤器的名字,也就是time_since
@register.filter(‘time_since’) # 注册过滤器 def time_since(value): if not isinstance(value,datetime): return value now=datetime.now() timestamp=(now-value).total_seconds() 这里获取到时间的秒数,然后用于后面的计算 if timestamp<60: return ‘刚刚’ elif timestamp>=60 and timestamp<60*60: minutes=int(timestamp/60) return ‘%s 分钟前’ % minutes elif timestamp>=60*60 and timestamp<60*60*24: hours=int(timestamp/60/60) return ‘%s 小时前’% hours elif timestamp>=60*60*24 and timestamp<60*60*24*30: days=int(timestamp/60/60/24) return ‘%s 天前’% days else: return value.strftime(‘%Y/%m/%d %H:%M’) 以上就是一个小小的实战例子