Template filter to format a start and end time in to a range. Uses Django's "P" format and assumes start and end time are on the same day or night before/morning after.
{{ start_time|time_range:end_time }}
Examples:
7-8 p.m.
8 p.m. - midnight
noon - 4 p.m.
9:45 a.m. - 5:15 p.m.
10:30 p.m. - 1:30 a.m.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | from django.utils.dateformat import time_format
@register.filter
def time_range(start_time, end_time):
"""Make time ranges like 7-9 p.m."""
if start_time is None:
return u''
if end_time is None or start_time == end_time:
return time_format(start_time, 'P')
if start_time.hour == 12 or start_time.hour == 0 \
or end_time.hour == 12 or end_time.hour == 0:
return u'%s - %s' % (time_format(start_time, 'P'), time_format(end_time, 'P'))
if (start_time.hour < 12 and end_time.hour >= 12) \
or (end_time.hour < 12 and start_time.hour >= 12):
return u'%s - %s' % (time_format(start_time, 'P'), time_format(end_time, 'P'))
first_part = time_format(start_time, 'P')
first_part = first_part.replace(' a.m.', '').replace(' p.m.', '')
return u'%s-%s' % (first_part, time_format(end_time, 'P'))
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.