Filter time format

Is there a way to use the filter {{date|timesince}} , but instead of two adjacent blocks display only one?

For example, my template currently displays "18 hours, 16 minutes." How do I get it to display 18 hours? (Rounding is not a concern here.) Thank you.

+8
django django-templates
source share
3 answers

I can't think of a simple built-in way to do this. Our own filter is often used here:

 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:',' }} 
+21
source share

Since the timesince filter does not accept any arguments, you will have to manually disable the clock from your date.

Here is a custom template filter that you can use to disconnect minutes, seconds, and microseconds from a 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 have not previously used a special filter or template tag, 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 is done by the standard python module).

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

+5
source share

Quick and dirty way:

Change the source file django $ 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 
-2
source share

All Articles