Fuzzy Time of Day

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from django import template
from bisect import bisect

register = template.Library()

@register.filter
def fuzzy_time(time):
    """
    Formats a time as fuzzy periods of the day.
    Accepts a datetime.time or datetime.datetime object.
    """
    periods = ["Early-Morning", "Morning", "Mid-day", \
               "Afternoon", "Evening", "Late-Night"]
    breakpoints = [4, 10, 13, 17, 21]
    try:
        return periods[bisect(breakpoints, time.hour)]
    except AttributeError: # Not a datetime object
        return '' #Fail silently

Comments

b23 (on June 9, 2008):

hi waylan,

nice snippet. In your description there is a little typo:

Posted in the {{ post.date|fuzzy_time }} of {{ post.date|date:"F j, Y"} }}

a closing bracket too much :)

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.