Python custom calculation time filter implementation process parsing
This article mainly introduces the implementation process analysis of Python custom computing time filter. It is introduced in great detail through the example code, which has certain reference value for everyone's study or work. Friends in need can refer to it
When writing custom filters, because Django template. Library. Filter () itself can be used as a decorator, so you can use:
register = django.template.Library() @register.filter 代替 register.filter("过滤器名","函数名")
If you use @ register Filter registers a custom filter and does not pass any parameters. The default filter name and function name are the same. Of course, they can also be modified, just in @ register Filter ("filter name"), the filter name is changed, and you can use a custom filter in the DTL template.
Define the display rules of time when the time calculation filter is displayed: how long is the time interval from time to now
The example code is as follows:
Custom filter file my_ fliter. py
@register.filter() def time_since(value): # 首先对传进来的时间进行判断,如果是datetime类型的就可以与当前的时间进行比较, # 如果不是datetime类型的,就直接返回value if not isinstance(value,datetime): return value # 如果可以到达这里,就代表为datetime类型的, # timedelay.total_seconds()属性 Now = datetime.Now() timestamp = (Now - value).total_seconds() if timestamp < 60: return "刚刚" elif timestamp >= 60 and timestamp < 60*60: # 在python3中如果两数相除,有余数的话,就会保持小数,这个时候我们就可以使用int()函数,进行转换 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")
views. Py, and construct a time:
from django.shortcuts import render from datetime import datetime def index(request): context = { 'time': datetime(year=2019,month=1,day=16,hour=23,minute=44,second=0) } return render(request,'index.html',context=context)
index. HTML:
{# 如果想要使用自定义的过滤器的话,就必须要先导入,导入的名称为自定义过滤器所处的文件名 #} {# 必须要把app安装到settings.py文件中 #} {% load my_fliter %} <!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Title</title> </head> <body> {{ time|time_since }} </body> </html>
View results in browser:
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.