Calculate the number of days between two dates inside Django templates

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

+6
source share
3 answers

Use timesince .

+11
source

Possible duplicate here

I would use the same method that lazerscience uses, something like this:

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
source

HTML Django. .

{{ to_date|timeuntil:from_date }}

.

0
source

All Articles