Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django create template filter for nice time

I know there's timesince filter.

But I want something that returns this:

  • just few seconds ago
  • X minutes ago
  • X hours ago
  • on $day_name
  • X weeks ago
  • X months ago

Examples:

  • just few seconds ago
  • 37 minutes ago
  • 2 hours ago
  • yesterday
  • on Thursday
  • 1 week ago
  • 7 months ago

How can I implement something like this?

like image 679
Fred Collins Avatar asked May 31 '11 23:05

Fred Collins


2 Answers

Not sure if it ticks all your boxes, but there's a tag naturaltime in the django.contrib.humanize template tags that should do this:

https://docs.djangoproject.com/en/dev/ref/contrib/humanize/#naturaltime

settings.py

INSTALLED_APPS = {
    ...
    'django.contrib.humanize',
}

template.html

{% load humanize %}
{{ model.timefield|naturaltime }}
like image 168
Timmy O'Mahony Avatar answered Oct 30 '22 18:10

Timmy O'Mahony


Edit: If you are using a recent SVN checkout of Django (post 1.3), see the answer by Pastylegs. Otherwise, here is what you can do:

I use repoze.timeago for this purpose. The code is fairly straightforward, so you could customize it if needed.

Here is a Django custom filter called elapsed that I created that uses repoze.timeago.

import datetime
from django import template
import repoze.timeago

register = template.Library()

# If you aren't using UTC time everywhere, this line can be used
# to customize repoze.timeago:
repoze.timeago._NOW = datetime.datetime.now

@register.filter(name='elapsed')
def elapsed(timestamp):
    """
    This filter accepts a datetime and computes an elapsed time from "now".
    The elapsed time is displayed as a "humanized" string.
    Examples:
        1 minute ago
        5 minutes ago
        1 hour ago
        10 hours ago
        1 day ago
        7 days ago

    """
    return repoze.timeago.get_elapsed(timestamp)
elapsed.is_safe = True
like image 22
Brian Neal Avatar answered Oct 30 '22 17:10

Brian Neal