Question

I'd like to write durations in my Django templates. This duration would be the difference between now() and an input date in my view.

The hard part is that I'd like to do it in a intelligent way. For examples:

  • if the duration < 60 mn, it should display "xx minutes ago"
  • if duration > 1 hour and < 1 day , it should display "xx hours ago"
  • and so on with "days", "months", "years".

Facebook posted news have this kind of behaviour. It makes no sens to write "this news was posted 2567 minutes ago", right?

The question is, how would you advise me to do this in Django? I was looking for a custom template or filter and didn't find anything.

What about custom tag? Or directly in classic Python method? As I don't prefer reinventing the wheel, any lib or snippet is welcome, of course :)

Thanks a lot.

Was it helpful?

Solution

You can use Django's built-in template filter timesince. I think it does exactly what you are describing, if used without argument.

If you want a little more "human" time, for example "an hour ago" instead of "1 hour ago", you can try the naturaltime filter from django.contrib.humanize, although it only works for seconds, minutes and hours.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top