计算Django模板中两个日期之间的天数

时间:2021-08-24 19:17:42

I have two dates and want to show a message like "n days left before your trial end." where n is a number of days between two given dates. Is that better to do this inside views or is there a quick way to do it inside template itself?

我有两个约会,并希望显示一条消息,例如“在试用期结束前n天”。其中n是两个给定日期之间的天数。在内部视图中执行此操作会更好吗?或者在模板内部有一个快速的方法吗?

2 个解决方案

#1


11  

Use timesince template tag.

使用timesince模板标签。

#2


1  

Possible duplicate here

这里可能重复

I'd actually use the same method lazerscience uses, something like this:

我实际上使用了lazerscience使用的相同方法,如下所示:

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

register = template.Library()

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

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

#1


11  

Use timesince template tag.

使用timesince模板标签。

#2


1  

Possible duplicate here

这里可能重复

I'd actually use the same method lazerscience uses, something like this:

我实际上使用了lazerscience使用的相同方法,如下所示:

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

register = template.Library()

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

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