How to display "x days ago" type time using Humanize in Django template?
Django has a built-in template filter timesince
that offers the same output you mentioned above. The following filter just strips the second part after the comma:
from datetime import datetime, timedelta
from django import template
from django.utils.timesince import timesince
register = template.Library()
@register.filter
def age(value):
now = datetime.now()
try:
difference = now - value
except:
return value
if difference <= timedelta(minutes=1):
return 'just now'
return '%(time)s ago' % {'time': timesince(value).split(', ')[0]}
You should duplicate your django.contrib.humanize.templatetags.humanize.py to myapp.templatetags.myhumanize and modify it to your needs. (I can't find the actual line that returns "x days, y hours ago". Which version of django/humanize are you using?)
There is naturaltime
in modern django.
Given now
is 17 Feb 2007 16:30:00
.
It changes 16 Feb 2007 13:31:29
to 1 day, 2 hours ago
.
{# some_template.html #}
{% load humanize %}
{{ past_time | naturaltime }}
https://docs.djangoproject.com/en/2.2/ref/contrib/humanize/#naturaltime