Examples of how to get the time difference from now in a Django template:
Table of contents
Time since now
Let's take for example the following model (defined in models.py file):
class Post(models.Model):
content = models.TextField()
date_created = models.DateTimeField(default=datetime.now)
and a view:
def my_view(request):
post_obj_list = Post.objects.all()
context = {'post_obj_list':post_obj_list}
return render(request, "myapp/post.html", context )
If we want to show the time since a post has been created in a django template a solution is to use timesince:
{% for post_obj in post_obj_list %}
{{ post_obj.date_created|timesince }}
{% endfor %}
It will show the time since now when the post has been created for example:
1 hour 19 minutes
Time since a given date
Note: it is also possible to get the time since agiven date using the following syntax:
{{ post_obj.date_created|timesince:thread_date }}
replace "thread_date" by a datetime object.