过滤时间的格式

Dav*_*542 10 django django-templates

有没有办法使用{{date|timesince}}过滤器,但不是有两个相邻的单位,只显示一个?

例如,我的模板当前显示"18小时16分钟".我怎么能让它显示"18小时"?(舍入不是这里的问题.)谢谢.

Ism*_*awi 25

我想不出一个简单的内置方法来做到这一点.这是我有时发现有用的自定义过滤器:

from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def upto(value, delimiter=None):
    return value.split(delimiter)[0]
upto.is_safe = True
Run Code Online (Sandbox Code Playgroud)

那你就可以做

{{ date|timesince|upto:',' }}
Run Code Online (Sandbox Code Playgroud)

  • @AndrewB.`split`的默认行为是在空格上拆分,在传递'None`时它会做同样的事情 (3认同)

Cas*_*par 5

由于timesince过滤器不接受任何参数,因此您必须手动剥离日期中的小时数.

这是一个自定义模板过滤器,可用于从日期时间对象中去除分钟,秒和微秒:

#this should be at the top of your custom template tags file
from django.template import Library, Node, TemplateSyntaxError
register = Library()

#custom template filter - place this in your custom template tags file
@register.filter
def only_hours(value):
    """
    Filter - removes the minutes, seconds, and milliseconds from a datetime

    Example usage in template:

    {{ my_datetime|only_hours|timesince }}

    This would show the hours in my_datetime without showing the minutes or seconds.
    """
    #replace returns a new object instead of modifying in place
    return value.replace(minute=0, second=0, microsecond=0)
Run Code Online (Sandbox Code Playgroud)

如果之前没有使用过自定义模板过滤器或标记,则需要在django应用程序中创建一个目录(即与models.py和views.py在同一级别)templatetags,并在其中创建一个名为的文件__init__.py(这使得标准的python模块).

然后,在其中创建一个python源文件,例如my_tags.py,将上面的示例代码粘贴到其中.在您的视图中,用于{% load my_tags %}让Django加载您的标记,然后您可以使用上面的过滤器,如上面的文档中所示.