简体   繁体   English

是否有Django模板过滤器将日期时间变为“5小时前”或“12天前”?

[英]Is there a Django template filter that turns a datetime into “5 hours ago” or “12 days ago”?

Let's say I have a datetime. 假设我有一个约会时间。 I do this: 我这样做:

Submitted on {{ post.date|date:"D. M d, P" }}

This actually prints the date. 这实际上打印了日期。 However, what if I want it to say, "4 hours ago" or "55 days ago" or "2 months ago"? 但是,如果我想说,“4小时前”或“55天前”或“2个月前”怎么办?

Try the template filter timesince . 试用模板过滤timesince

Use it like this: 像这样使用它:

{{ mytemplatevar|timesince }}

UPDATED: We can assume that you have a post_date attribute saved in your model capturing the time you save the post. 更新:我们可以假设您在模型中保存了post_date属性,捕获了保存帖子的时间。 present.time is the current time that is loaded freshly onto the template when one visits the post. present.time是当访问帖子时新加载到模板上的当前时间。 This would be the recommended implementation of what you are looking for: 这将是您正在寻找的建议实施

Submitted on {{ present.date|timesince:post_date }} ago.

Try this snippet . 试试这个片段 It is not built in django before 1.3 它不是在1.3之前的django中构建的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM