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?
Answers:
Use timesince template tag.
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]}
This code for HTML in Django. You can easily find the remaining days.
{{ to_date|timeuntil:from_date }}
Otherwise, you can use custom TemplateTags.
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
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?
Use timesince template tag.
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]}
This code for HTML in Django. You can easily find the remaining days.
{{ to_date|timeuntil:from_date }}
Otherwise, you can use custom TemplateTags.
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