I wrote my own time_utils.py
in an app called custom_utils
like below based on stack overflow posts. You can modify it accordingly.
import datetime
from django.utils import timezone
def prettydate(d):
if d is not None:
diff = timezone.now() - d
s = diff.seconds
if diff.days > 30 or diff.days < 0:
return d.strftime('Y-m-d H:i')
elif diff.days == 1:
return 'One day ago'
elif diff.days > 1:
return '{} days ago'.format(diff.days)
elif s <= 1:
return 'just now'
elif s < 60:
return '{} seconds ago'.format(s)
elif s < 120:
return 'one minute ago'
elif s < 3600:
return '{} minutes ago'.format(round(s/60))
elif s < 7200:
return 'one hour ago'
else:
return '{} hours ago'.format(round(s/3600))
else:
return None
then in the app models, I do:
from custom_utils.time_utils import prettydate
class ForumPost(models.Model):
# your other fields
published_date = models.DateTimeField(blank=True, null=True)
# your other fields
def pretty_published_date(self):
return prettydate(self.published_date)
reference: #Natural/Relative days in Python
Jose Segall's answer
EDIT: I faced a problem when querying a dataset using annotate, I was not able to use attributes such as the pretty_published_date
. I had to use custom template tags. The following is how to implement prettydate
function to custom template tags.
- Create
templatetags
folder in one of the app which is in INSTALLED_APPS in settings file of the project. I put mine under forum
folder.
- Create a blank
__init__.py
file inside templatetags
folder
- Create
custom_tags.py
- Inside
custom_tags.py
, add the prettydate
function
from django import template
import datetime
from django.utils import timezone
register = template.Library()
@register.filter
def prettydate(d):
if d is not None:
# the rest of the function
in template file,
{% load custom_tags %}
{{forumpost.max_activity|prettydate}}
Also make sure that you restart the Django development server. If the server does not restart, Django won't register the tags.