tags:

views:

77

answers:

3

The Django date template filter takes the format character "a" for "a.m." and "A" for "AM". How do you get lower case without periods or upper case with the periods?

You can use lower and upper filters, but they will mess with month and day of the week formatting.

A: 

Best way would be to write a custom template filter.

Documentation here

Mayuresh
+1  A: 

you can create your own filter so your templates will look like this:

{{ value|date:"D d M Y" }} {{ value|meridiem:"u" }}

where meridiem could be:

def meridiem(value, arg="ld"):
    if not value:
        return u''
    if 'u' in arg:
        if 'd' in arg:
            return 'A.M.'
        return 'AM'
    else:
        if 'd' in arg:
            return 'a.m.'
        return 'am'

this is not really elegant but could be a simple solution. beware that i did not test the code.

mg
+3  A: 

Alternately you could inherit the base functionality and simply add the output you're looking for. (again with a custom filter).

Here's a custom template fitler which adds a new argument 'c' that will change (get it, c... change) the functional of a/A. It basically serves as a switch to toggle the functionality of a/A. That's hard to explain. Here's some examples:

{{ datetime|smartdate:"h:i A" }} = '12:30 AM'
{{ datetime|smartdate:"h:i Ac" }} = '12:30 A.M.'
{{ datetime|smartdate:"h:i a" }} = '12:30 a.m.'
{{ datetime|smartdate:"h:i ac" }} = '12:30 am'

And here's the filter...

import re
from django.template.defaultfilters import date as date_filter

# --------------------------------------------------------------------------------
#   |smartdate:"date format" -- new arg 'c' (change) alteras the AM/pm appearance
# --------------------------------------------------------------------------------
@register.filter
def smartdate(value, arg):
    rendered = date_filter(value, arg)
    if 'c' in arg:
        rendered = re.sub('(a|p)\.m\.c', lambda m: '%sm' % m.group(1), rendered)
        rendered = re.sub('(A|P)Mc', lambda m: '%s.M.' % m.group(1), rendered)
    return rendered

Edit -- Slightly optimized the filter

T. Stone
+1, this is the way to go.
celopes
Thanks for the answer. This is perfect. It's a serious oversight that the built-in filter cannot handle this situation.
hekevintran