【问题标题】:Format timesince filter to only show minutes - Django格式化时间过滤器以仅显示分钟 - Django
【发布时间】:2015-11-22 02:25:24
【问题描述】:

有没有办法将 Django 中的timesince 过滤器格式化为仅以分钟为单位输出值?

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

提前谢谢你!

【问题讨论】:

  • 不编写自定义过滤器就无法完成。

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


【解决方案1】:

timesince 的缩短版本。在我的情况下,只需要 年或月。 此代码应该在您的 appname/templatetags/custom_filters.py 文件中,然后您将其加载到模板中作为 {% load custom_filters %} 并使用与 timesince {{ 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. 在模板标签文件夹中包含 __init__.py。 2.修改自定义标签时重启服务器
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2012-06-16
    • 2021-10-11
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 2020-09-08
    相关资源
    最近更新 更多