Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

python - How to display "x days ago" type time using Humanize in Django template?

When I do this:

{% load humanize %}

{{ video.pub_date|naturaltime|capfirst }}

I get 2 days, 19 hours ago

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...