Python: ¿Cómo formateo una fecha en Jinja2?


Usando Jinja2, ¿cómo formateo un campo de fecha? Sé que en Python simplemente puedo hacer esto:

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

Pero, ¿cómo formateo la fecha en Jinja2? Gracias.

 155
Author: Ambrosio, 2011-01-28

7 answers

Hay dos maneras de hacerlo. El enfoque directo sería simplemente llamar (e imprimir) el método strftime() en su plantilla, por ejemplo

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

Otro enfoque ligeramente mejor sería definir su propio filtro, por ejemplo:

from flask import Flask
import babel

app = Flask(__name__)

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)

app.jinja_env.filters['datetime'] = format_datetime

(Este filtro se basa en babel por razones relacionadas con i18n, pero también puede usar strftime). La ventaja del filtro es que puede escribir

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

Que se ve mejor y es más fácil de mantener. Otro filtro común es también el filtro" timedelta", que evalúa algo así como "escrito hace 8 minutos". Puede usar babel.dates.format_timedelta para eso, y registrarlo como filtro similar al ejemplo datetime dado aquí.

 270
Author: tux21b,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-20 23:46:28

Aquí está el filtro que terminé usando para strftime en Jinja2 y Flask

@app.template_filter('strftime')
def _jinja2_filter_datetime(date, fmt=None):
    date = dateutil.parser.parse(date)
    native = date.replace(tzinfo=None)
    format='%b %d, %Y'
    return native.strftime(format) 

Y luego utilizas el filtro así:

{{car.date_of_manufacture|strftime}}
 19
Author: Raj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-09 13:36:42

Creo que tienes que escribir tu propio filtro para eso. En realidad es el ejemplo de filtros personalizados en la documentación: http://jinja.pocoo.org/docs/api/#custom-filters

 16
Author: Brian Goldman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-28 16:29:11

Si está tratando con un objeto de tiempo de nivel inferior (a menudo solo uso enteros), y no quiero escribir un filtro personalizado por cualquier razón, un enfoque que uso es pasar la función strftime a la plantilla como una variable, donde se puede llamar donde lo necesite.

Por ejemplo:

import time
context={
    'now':int(time.time()),
    'strftime':time.strftime }  # Note there are no brackets () after strftime
                                # This means we are passing in a function, 
                                # not the result of a function.

self.response.write(jinja2.render_template('sometemplate.html', **context))

Que luego se puede usar dentro de sometemplate.html:

<html>
    <body>
        <p>The time is {{ strftime('%H:%M%:%S',now) }}, and 5 seconds ago it was {{ strftime('%H:%M%:%S',now-5) }}.
    </body>
</html>
 12
Author: Olly F-G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-29 00:01:39

Usuarios del Motor de Google App : Si se está moviendo de Django a Jinja2, y está buscando reemplazar el filtro de fecha, tenga en cuenta que los códigos de formato % son diferentes.

Los códigos strftime % están aquí: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

 4
Author: Andrew Murphy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-06 23:10:18

Ahora puedes usarlo así en la plantilla sin ningún filtro

{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}
 1
Author: Zaytsev Dmitry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-09 20:18:17

En frasco, con babel, me gusta hacer esto:

@app.template_filter('dt')
def _jinja2_filter_datetime(date, fmt=None):
    if fmt:
        return date.strftime(fmt)
    else:
        return date.strftime(gettext('%%m/%%d/%%Y'))

Utilizado en la plantilla con {{mydatetimeobject|dt}}

Así que no con babel puede especificar sus diversos formatos en los mensajes.po como este por ejemplo:

#: app/views.py:36
#, python-format
msgid "%%m/%%d/%%Y"
msgstr "%%d/%%m/%%Y"
 0
Author: euri10,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-11 16:15:57