How to compare two dates on a Django site
How to compare two dates on a Django site
Published on: (Updated on: )
Sometimes you might want to compare two dates on a Django site or blog in other to show the last updated date or time. There are several ways to do this but this post shows you how to compare two dates in Django template with just a few lines of code.
Step 1
If you have not created a date and last updated time in your Django database, add the following in your relevant models.py:
published = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(auto_now=True)
The first line of code (published) will add the date your post was published and the second line of code (last_update) will add the last time your post was updated.
Step 2
To compare dates with python on your Django site, add the following code in your Django template:
{% if post.last_update|date:"dmYHis" > post.published|date:"dmYHis" %} | Updated on {{ post.last_update|date }} {% endif %}
What the above code does:
The code basically converts both dates to numerical values and compares them. If post.last_update is greater than post.published, the last updated date will be displayed on your Django site or blog.