Skip to content

Instantly share code, notes, and snippets.

@lightstrike
Created July 17, 2014 15:37
Show Gist options
  • Save lightstrike/908bd83b6c18dff8141e to your computer and use it in GitHub Desktop.
Save lightstrike/908bd83b6c18dff8141e to your computer and use it in GitHub Desktop.
Days Until Filter in Django
# Inspiration from https://djangosnippets.org/snippets/116/
from django import template
import datetime
register = template.Library()
def days_until(value):
"""
Returns number of days between value and today
Example usage in template:
{% load days_until %}
{{ ending_time|daysuntil }}
"""
today = datetime.date.today()
try:
diff = value - today
except TypeError:
# convert datetime.datetime to datetime.date
diff = value.date() - today
if diff.days > 1:
return '{days}d'.format(days=diff.days)
elif diff.days == 0:
return 'expires today'
else:
# Date is in the past; return expired message
return 'expired'
register.filter('daysuntil', days_until)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment