Calculate number of days between two dates inside Django templates

Question:

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?

Asked By: Sergei Basharov

||

Answers:

Use timesince template tag.

Answered By: spicavigo

Possible duplicate here

I’d actually use the same method 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]}
Answered By: Sindri Guðmundsson

This code for HTML in Django. You can easily find the remaining days.

{{ to_date|timeuntil:from_date }}

Otherwise, you can use custom TemplateTags.

Answered By: jahurul25

In the HTML template, you can do the following:

{{ comments.created|timeuntil:project.created }} 

And you get output something like this:

1 hour, 5 minutes
Answered By: 2TZ
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.