开发者

How to display "This many months ago" in Django using Humanize?

I have this variable:

{{ video.pub_date }}

which outputs:

May 16, 2011, 2:03 p.m.

How can I get it to show:

1 month ago

I have loaded humanize on the p开发者_C百科age, but the django docs for humanize doesn't really show how to implement it to show what I want:

https://docs.djangoproject.com/en/dev/ref/contrib/humanize/

It just says that it's possible at the bottom of the page there.


You have to have the development version of Django to use the naturaltime filter

{% load humanize %}
{{ video.pub_date|naturaltime }}

Humanize isn't a template tag, it's a library of template filters which means when you load it you have access to various other filters included in the module.

Alternatively you can use the timesince filter withouth having to load any other template tag libraries

{{ video.pub_date|timesince }}


{{ video.pub_date|timesince }} ago

From the docs at timesince

timesince

Formats a date as the time since that date (e.g., "4 days, 6 hours").

Takes an optional argument that is a variable containing the date to use as the comparison point (without the argument, the comparison point is now). For example, if blog_date is a date instance representing midnight on 1 June 2006, and comment_date is a date instance for 08:00 on 1 June 2006, then {{ blog_date|timesince:comment_date }} would return "8 hours".

Comparing offset-naive and offset-aware datetimes will return an empty string.

Minutes is the smallest unit used, and "0 minutes" will be returned for any date that is in the future relative to the comparison point.


To activate what filter. adds 'django.contrib.humanize' to your INSTALLED_APPS setting,

Once you’ve done that,

use {% load humanize %} in a templates, and you’ll have access to the follow filters,

{{comment.timestamp | naturaltime }}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜