如何显示“x天前”在Django模板中使用Humanize键入时间? [英] How to display "x days ago" type time using Humanize in Django template?

查看:353
本文介绍了如何显示“x天前”在Django模板中使用Humanize键入时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我这样做:

{% load humanize %}

{{ video.pub_date|naturaltime|capfirst }}

我得到 2天,19小时前

如何在没有时间的情况下只得2天。基本上,如果视频在不到一天前发布,那么应该说X小时前,那么它应该在X天前几天,然后几个星期。我只是不想要1小时5分钟前或2天13分钟前。只是第一部分。

How can I get just 2 days without the hours. Basically if the video was published in less than a day ago then it should say X hours ago, then it should count in days like X days ago, then in weeks. I just don't want 1 hours 5 minutes ago or 2 days 13 minutes ago. Just the first part.

我看过人性化的文档,但找不到我需要的东西。

I looked at the humanize docs but couldn't find what I needed.

推荐答案

Django已内置模板过滤器 timesince ,提供与上述相同的输出。以下过滤器仅在逗号后面删除第二部分:

Django has a built-in template filter timesince that offers the same output you mentioned above. The following filter just strips the second part after the comma:

from datetime import datetime, timedelta
from django import template
from django.utils.timesince import timesince

register = template.Library()

@register.filter
def age(value):
    now = datetime.now()
    try:
        difference = now - value
    except:
        return value

    if difference <= timedelta(minutes=1):
        return 'just now'
    return '%(time)s ago' % {'time': timesince(value).split(', ')[0]}

这篇关于如何显示“x天前”在Django模板中使用Humanize键入时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆