from django import template
from datetime import datetime
register = template.Library()
@register.filter
def time_since(value):
if not isinstance(value,datetime):
print(1)
return value
"""
time距离现在的时间间隔
1. 如果时间间隔小于1分钟以内,那么就显示“刚刚”
2. 如果是大于1分钟小于1小时,那么就显示“xx分钟前”
3. 如果是大于1小时小于24小时,那么就显示“xx小时前”
4. 如果是大于24小时小于30天以内,那么就显示“xx天前”
5. 以上都不是则返回具体的时间
"""
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:%S')
# 测试用数据
date_now = datetime(year=2019,month=4,day=1,hour=21,minute=36,second=53)
print(time_since(date_now))