[Fixed]-Format of timesince filter

30👍

I can’t think of a simple builtin way to do this. Here’s a custom filter I’ve sometimes found useful:

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

Then you could just do

{{ date|timesince|upto:',' }}

5👍

Since the timesince filter doesn’t accept any arguments, you will have to manually strip off the hours from your date.

Here is a custom template filter you can use to strip off the minutes, seconds, and microseconds from your datetime object:

#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)

If you haven’t used a custom template filter or tag before, you will need to create a directory in your django application (i.e. at the same level as models.py and views.py) called templatetags, and create a file inside it called __init__.py (this makes a standard python module).

Then, create a python source file inside it, for example my_tags.py, and paste the sample code above into it. Inside your view, use {% load my_tags %} to get Django to load your tags, and then you can use the above filter as shown in the documentation above.

👤Caspar

0👍

Well, you can make use of JS here. You need to add a script that splits the first and second units and then displays only the first one.

Say the part of your template looks like this:

<your_tag id="your_tag_id">{{date|timesince}}</your_tag>

Now, add the below script to your template.

<script>
        let timesince = document.getElementById("your_tag_id").innerHTML.split(",");
        document.getElementById("your_tag_id").innerHTML = timesince[0];
</script>
👤jag

-3👍

A quick and dirty way:

Change the django source file $PYTHON_PATH/django/utils/timesince.py @line51(django1.7) :

result = avoid_wrapping(name % count)
return result  #add this line let timesince return here
if i + 1 < len(TIMESINCE_CHUNKS):
    # Now get the second item
    seconds2, name2 = TIMESINCE_CHUNKS[i + 1]
    count2 = (since - (seconds * count)) // seconds2
    if count2 != 0:
        result += ugettext(', ') + avoid_wrapping(name2 % count2)
return result  

Leave a comment