Django creates a template filter for a nice time

I know the timesince filter.

But I want something that returns this:

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

Examples:

  • just a 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?

+6
source share
2 answers

Not sure if it will check all of your fields, but there is a naturaltime tag 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 }} 
+14
source

Edit: if you are using a recent Django SVN check (post 1.3), see Pastylegs answer. Otherwise, here is what you can do:

I use repoze.timeago for this purpose. The code is pretty simple, so you can configure it if necessary.

Here is a custom Django 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 
+4
source

Source: https://habr.com/ru/post/889497/


All Articles