Login

Time ranges like 7-9 p.m.

Author:
sgb
Posted:
January 17, 2008
Language:
Python
Version:
.96
Score:
3 (after 3 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.