Skip to content

Instantly share code, notes, and snippets.

@abhiabhi94
Last active February 8, 2020 12:30
Show Gist options
  • Save abhiabhi94/b75c2d479c83a23655dd34fd30597e33 to your computer and use it in GitHub Desktop.
Save abhiabhi94/b75c2d479c83a23655dd34fd30597e33 to your computer and use it in GitHub Desktop.
A django template tag display time in a more intutive format e.g. Just now, 2 hours ago, 3 weeks ago etc. Makes use of the default timesince filter in django.
from datetime import timedelta
from django import template
from django.utils import timezone
from django.utils.timesince import timesince
register = template.Library()
@register.filter(name='cool_timesince', is_safe=False)
def cool_timesince(val, now=1):
"""
Converts the time into a more human readable format.
It makes uses of django's {timesince} template and removes the extra information from it.
Returns:
str: time in a more human readable format.
Params:
val: a datetime object
now: int
a constraint in ***minutes*** that decides for upto what values 'Just now' will be returned.
"""
if not val:
return ''
current_time = timezone.now()
try:
diff = current_time - val
except (ValueError, TypeError):
return val
if diff <= timedelta(minutes=now):
return 'Just now'
return f'{timesince(val).split(", ")[0]} ago'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment