Login

Fuzzy Time of Day

Author:
waylan
Posted:
June 13, 2007
Language:
Python
Version:
.96
Score:
3 (after 3 ratings)

This filter will display the time as word(s) indicating roughly the time of day ("Morning", "Afternoon", "Evening", etc). For example, the following template snippet:

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

will result in the following (assuming post.date == datetime.datetime(2007, 6, 13, 20, 57, 55, 765000)):

Posted in the evening of June 13, 2007.

The terms used and breakpoints (hours only) can be rather arbitrary so you may want to adjust them to your liking. See the docs for bisect for help in understanding the code. Just remember you should have one less breakpoint than periods and the first breakpoint falls at the end of the first period. The idea was inspired by Dunstan Orchard, although the code is very different (php case statement). He uses quite a bit more periods in a day, so you might want to take a look.

 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

More like this

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

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 :)

#

Please login first before commenting.