8

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?

Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335

4 Answers4

14

Use timesince template tag.

spicavigo
  • 4,116
  • 22
  • 28
4

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

{{ to_date|timeuntil:from_date }}

Otherwise, you can use custom TemplateTags.

Chandresh Khambhayata
  • 1,748
  • 2
  • 31
  • 60
jahurul25
  • 159
  • 4
1

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]}
Community
  • 1
  • 1
Sindri Guðmundsson
  • 1,253
  • 10
  • 24
0

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
Antoine
  • 1,393
  • 4
  • 20
  • 26
2TZ
  • 1
  • 1