Created
July 17, 2014 15:37
-
-
Save lightstrike/908bd83b6c18dff8141e to your computer and use it in GitHub Desktop.
Days Until Filter in Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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