Django Filter To Shorten Naturaltime

Estimated time to read: 1 minute

  • This is a filter snippet to shorten the natural time value obtained using naturaltime function from humanize.
#In templatetag file , say file_tags.py
from django import template
register = template.Library()

@register.filter
def shorten_naturaltime(naturaltime):
    naturaltime = naturaltime.replace('minutes','m').replace('hours','h').replace('days','d')
    naturaltime = naturaltime.replace('months','mon').replace('weeks','w').replace('week','w')
    return naturaltime

#In Usage file
{% load file_tags %} 
{{start_time|naturaltime|shorten_naturaltime}} #where start_time is the datetime object to be modified

{% if page.comments %}

{% endif %}