I know there's timesince
filter.
But I want something that returns this:
Examples:
How can I implement something like this?
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 }}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With