Login

Time ranges like 7-9 p.m.

Author:
sgb
Posted:
January 17, 2008
Language:
Python
Version:
.96
Tags:
format time range
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. mkrange - create a range() inside a template by wolever 5 years ago
  2. Template range loop by nfg 5 years, 1 month ago
  3. Format date range by bmihelac 5 years, 11 months ago
  4. Page numbers with ... like in Digg by Ciantic 5 years, 10 months ago
  5. Improved many-page pagination by dokterbob 4 years, 5 months ago

Comments

Please login first before commenting.