Django自定义时间过滤器

在app下新建templatetags  (Pthon package) 并且新建自定义Py文件
Django自定义时间过滤器_第1张图片

编写自定义Py文件

# !/usr/bin/env python 
# -*- coding:utf-8 -*-
__author__ = '_X.xx_'
__date__ = '2018/7/24 21:52'
from datetime import datetime
from django import template
from django.utils.timezone import now as now_func
register = template.Library()
@register.filter
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')

 

 

编写app下views视图文

from datetime import datetime
from django.shortcuts import render


def index(request):
    # 给定一个时间
    context = {
        'my_time': datetime(year=2018, month=7, day=7, hour=16, minute=7, second=0)
    }
    return render(request, 'index.html', context=context)

 

编写Template下html文件调用自定义的过滤器


{% load my_filter %}


    
    Title


    {{ my_time|time_since }}

Django自定义时间过滤器_第2张图片

 

 

 

你可能感兴趣的:(Django)