从Django Timesince中删除尾随数据 [英] Remove trailing data from Django timesince

查看:191
本文介绍了从Django Timesince中删除尾随数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从django timesince 过滤器中删除尾随数据?

Is there a way to remove the trailing data from the django timesince filter?

我想只显示几天,几周或几年,没有任何尾随信息。例如周+天 - >周,月+周 - >月,年+月 - >年等。

I would like to only display days, weeks months or years without any trailing information. e.g weeks + days -> weeks, months + weeks -> months, years + months -> years, etc.

此外,如果日期不到一天,应该显示小时数。例如1小时前,4小时前,等等。

Additionally, if the date is less than one day, it should display the hours. e.g. 1 hour ago, 4 hours ago, etc.

目前我有一个datetime对象,正在使用这样的过滤器:

Currently I have a datetime object and am using the filter like this:

{{ my_date_time|timesince}}


推荐答案

您可以制作自己的模板标签,并使用它来修改 timesince 的输出,使其成为您喜欢的任何内容。这个例子只是为了让你开始:

You can make your own template tag and use it to modify the output of timesince to be anything you like. Here's an example just to get you started:

def custom_timesince(value):
    now = datetime.datetime.now()
    # can add some error checking if you want
    diff = now - value
    if diff < timedelta(days=1):
        return "recently" # or w/e you wanted with the hours

    # remove trailing information from timesince    
    return timesince(value).split(", ")[0]

可能有帮助:使用这样的自定义标签的文档

这篇关于从Django Timesince中删除尾随数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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