Django date filter to display "am" or "AM"

Django's date template filter accepts a character of format "a" for "am" and "A" for "AM". How to get lower case without periods or upper case with periods?

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

+3
source share
3 answers

Alternatively, you can inherit the basic functionality and just add the output you are looking for. (again with a custom filter).

, 'c', ( , c... ) a/A. a/A. . :

{{ 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'

...

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

-

+4

, :

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

:

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'

, . .

+1

The best way is to write a custom template filter.

Documentation here

0
source

Source: https://habr.com/ru/post/1725695/


All Articles