Login

Optimized humanize naturalday filter

Author:
c2j
Posted:
September 12, 2009
Language:
Python
Version:
1.1
Tags:
original-bug-fixes
Score:
1 (after 1 ratings)

In Django humanize naturalday filter, you could not get the time part since a programming issue, If you apply it like: {% load humanize %} {{ response.date_submitted|naturalday:"Y/n/j H:i" }}

You can get 'today', 'yesterday', 'tomorrow' or empty, but you can not get such as '2009/9/10 11:56'

So I change it like above code. Now you can get 'today', 'yesterday', 'tomorrow' or '2009/9/10 11:56'

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from django.utils.translation import ungettext, ugettext as _
from django.utils.encoding import force_unicode
from django import template
from django.template import defaultfilters
from datetime import date
import re

register = template.Library()

def mynaturalday(value, arg=None):
    """
    For date values that are tomorrow, today or yesterday compared to
    present day returns representing string. Otherwise, returns a string
    formatted according to settings.DATE_FORMAT.
    """
    try: 
        value1 = date(value.year, value.month, value.day)
    except AttributeError:
        # Passed value wasn't a date object
        return value
    except ValueError:
        # Date arguments out of range
        return value
    delta = value1 - date.today()
    if delta.days == 0:
        return _(u'today')
    elif delta.days == 1:
        return _(u'tomorrow')
    elif delta.days == -1:
        return _(u'yesterday')
    return defaultfilters.date(value, arg)
register.filter(mynaturalday)

More like this

  1. Humanized and localized timesince template filter by slink 4 years, 5 months ago
  2. Pattern to integer list function by marinho 7 years, 4 months ago
  3. Integer list to pattern function by marinho 7 years, 4 months ago
  4. datemate by catellar 3 years, 8 months ago
  5. Date/time util template filters by marinho 7 years, 5 months ago

Comments

Please login first before commenting.