Immortal Noob
Immortal Noob

Reputation: 41

How to get time elapsed since creation date of an object(post) in django?

I tried looking through the documentation for a datetime formating that would allow me to show the time elapsed since a post was created e.g "created 15s ago" but I couldn't find one. I figured I had to create a custom filter but I don't have a clue on how to go about it. I am also new to the Django framework unfortunately.

Upvotes: 1

Views: 1389

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476584

Django has a |timesince template tag [Django-doc], this formats the time since an event in a "human" way. You thus can format this in the template with:

{{ post.created|timesince }} ago

For example:

>>> print(Template('{{ foo|timesince }} ago').render(Context({'foo': datetime(2021, 2, 20, 21, 15)})))
0 minutes ago
>>> print(Template('{{ foo|timesince }} ago').render(Context({'foo': datetime(2021, 2, 20, 21, 14)})))
1 minute ago
>>> print(Template('{{ foo|timesince }} ago').render(Context({'foo': datetime(2021, 2, 20, 21, 10)})))
5 minutes ago
>>> print(Template('{{ foo|timesince }} ago').render(Context({'foo': datetime(2021, 2, 20, 20, 10)})))
1 hour, 5 minutes ago

Since Django runs as backend, this will however not update the content if the page does not refresh. For more dynamic ways, you should look for a JavaScript library where you thus pass the datetime in a standardized way, and let JavaScript fill in the amount of time that has passed.

Upvotes: 3

Related Questions