Django自定义时间过滤器

1.创建apps/news/templatetags/datetime_filter.py文件

import pytz

from django import template
from datetime import datetime

register = template.Library()


# 时间过滤器
@register.filter()
def time_filter(data):
    if isinstance(data, datetime):
        now = datetime.now()  # 不含时区
        # print('最新:{}'.format(now))
        now = now.replace(tzinfo=pytz.timezone('UTC'))
        # print('数据库时间:{}'.format(data))
        timestamp = (now-data).total_seconds()
        # print('时间差:{}'.format(timestamp))
        if timestamp < 60:
            return '刚刚'

        elif timestamp>=60 and timestamp<60*60:
            m = int(timestamp//60)
            return '{}分钟前'.format(m)

        elif timestamp>=60*60 and timestamp<60*60*24:
            h = int(timestamp//(60*60))
            return '{}小时前'.format(h)

        elif timestamp>=60*60*24 and timestamp<60*60*24*30:
            d = int(timestamp//(60*60*24))
            return '{}天前'.format(d)

        elif timestamp>=60*60*24*30 and timestamp<60*60*24*7*52:
            month = int(timestamp//(60*60*24*30))
            return '{}月前'.format(month)

        elif timestamp>=60*60*24*7*52 and timestamp<60*60*24*7*52*2:
            y = int(timestamp//(60*60*24*7*52))
            return '{}年前'.format(y)

        elif timestamp>60*60*24*7*52*2:
            return '凉了'

        else:
            return data.strftime('%Y年%m月%d日 %H:%M')
    else:
        return data

2.在html模板里面

{% load dataetime_filter %}

{{ update_time|time_filter }}

 

posted @ 2020-04-27 15:05  不会飞的鲨鱼  阅读(646)  评论(0编辑  收藏  举报