[Fixed]-Format timesince filter to only show minutes – Django

1👍

A shortened version of timesince. In my case only years or months needed.
This code should be in your appname/templatetags/custom_filters.py file, then you load it in template as {% load custom_filters %} and use the same way as timesince {{ comment.timestamp|yearssince }}
So, here is your 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
👤horbor

0👍

No, it’s not possible to do this with Django’s built in timesince filter. It has one optional argument which is a date to compare to, so it’s not possible to specify the output format.

You could write your own custom filter that does this. You should be able to reuse a lot of the code in the timesince filter and django.utils.timesince.timesince.

Leave a comment