Skip to main content
 首页 » 编程设计

python之从 Django timesince 中删除尾随数据

2024年10月01日39Leo_wl

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

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

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

目前我有一个日期时间对象并且正在使用这样的过滤器:

{{ my_date_time|timesince}} 

请您参考如下方法:

您可以创建自己的模板标签并使用它来将 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