How to Format a Date in Jinja2

How do I format a date in Jinja2?

There are two ways to do it. The direct approach would be to simply call (and print) the strftime() method in your template, for example

{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}

Another, sightly better approach would be to define your own filter, e.g.:

from flask import Flask
import babel

app = Flask(__name__)

@app.template_filter()
def format_datetime(value, format='medium'):
if format == 'full':
format="EEEE, d. MMMM y 'at' HH:mm"
elif format == 'medium':
format="EE dd.MM.y HH:mm"
return babel.dates.format_datetime(value, format)

(This filter is based on babel for reasons regarding i18n, but you can use strftime too). The advantage of the filter is, that you can write

{{ car.date_of_manufacture|format_datetime }}
{{ car.date_of_manufacture|format_datetime('full') }}

which looks nicer and is more maintainable. Another common filter is also the "timedelta" filter, which evaluates to something like "written 8 minutes ago". You can use babel.dates.format_timedelta for that, and register it as filter similar to the datetime example given here.

Format date with Jinja2 and python

You can implement a python function that will handle the date.

You can consume it from your template.

Example:

def reverse_date(a_date):
d = a_date.split('-')
d.reverse()
reverse_d = '-'.join(d)
return reverse_d

template = Template('your template')
template.globals['reverse_date'] = reverse_date
# now you can use it in your template
{{ reverse_date(date['Fundação']) }}


Related Topics



Leave a reply



Submit