从Django timesin删除尾随数据

2024-06-20 15:07:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我只想显示天,周,月或年没有任何跟踪信息。e、 g周+天->周,月+周->月,年+月->年,等等

另外,如果日期少于一天,它应该显示小时数。e、 一小时前,四小时前,等等

目前我有一个日期时间对象,并使用如下过滤器:

{{ my_date_time|timesince}}

Tags: 数据对象信息过滤器datetimemy时间
1条回答
网友
1楼 · 发布于 2024-06-20 15:07:31

您可以创建自己的模板标记,并使用它将timesince的输出修改为您喜欢的任何内容。下面是一个简单的例子:

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]

可能有帮助:docs on using such custom tags

相关问题 更多 >