格式化时间因为过滤器只显示分钟 - Django

时间:2015-08-27 15:41:48

标签: django django-templates django-template-filters

有没有办法在Django中格式化timesince过滤器,只能以分钟为单位输出值?

例如,{{ comment.timestamp|timesince }}显示3 days, 4 hours。我希望它显示1680 minutes

提前谢谢!

2 个答案:

答案 0 :(得分:1)

缩短版的timesince。在我的情况下,只需年或数月。 此代码应位于appname / templatetags / custom_filters.py文件中,然后将其作为{% load custom_filters %}加载到模板中,并使用与{{ comment.timestamp|yearssince }}时间相同的方式 所以,这是你的custom_filters.py

from __future__ import unicode_literals
import datetime
from django import template
from django.utils.html import avoid_wrapping
from django.utils.timezone import is_aware, utc
from django.utils.translation import ugettext, ungettext_lazy

register = template.Library()
TIMESINCE_CHUNKS = (
    (60 * 60 * 24 * 365, ungettext_lazy('%d year', '%d years')),
    (60 * 60 * 24 * 30, ungettext_lazy('%d month', '%d months')),
)
@register.filter
def yearssince(d, now=None):
    # Convert datetime.date to datetime.datetime for comparison.
    if not isinstance(d, datetime.datetime):
        d = datetime.datetime(d.year, d.month, d.day)
    if now and not isinstance(now, datetime.datetime):
        now = datetime.datetime(now.year, now.month, now.day)

    if not now:
        now = datetime.datetime.now(utc if is_aware(d) else None)

    delta = now - d
    # ignore microseconds
    since = delta.days * 24 * 60 * 60 + delta.seconds
    if since <= 0:
        # d is in the future compared to now, stop processing.
        return avoid_wrapping(ugettext('0 minutes'))
    for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS):
        count = since // seconds
        if count != 0:
            break
    result = avoid_wrapping(name % count)

    return result

答案 1 :(得分:0)

不,使用内置timesince过滤器的Django无法做到这一点。它有一个可选参数,它是要比较的日期,因此无法指定输出格式。

您可以编写自己的custom filter来执行此操作。您应该能够重复使用timesince过滤器和django.utils.timesince.timesince中的大量代码。