本文介绍了如何在Jinja2中格式化日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Jinja2,如何格式化日期字段?我知道在Python中我可以简单地做到这一点:

Using Jinja2, how do I format a date field? I know in Python I can simply do this:

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

但是如何在Jinja2中格式化日期?

But how do I format the date in Jinja2?

推荐答案

有两种方法可以做到这一点.直接的方法是简单地调用(并打印)模板中的strftime()方法,例如

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)

(出于与i18n有关的原因,此过滤器基于babel,但您也可以使用strftime).过滤器的优点是,您可以编写

(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|datetime }}
{{ car.date_of_manufacture|datetime('full') }}

看起来更好,更易于维护.另一个常见的过滤器也是"timedelta"过滤器,其计算结果类似于"8分钟前编写".您可以使用babel.dates.format_timedelta并将其注册为类似于此处给出的日期时间示例的过滤器.

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.

这篇关于如何在Jinja2中格式化日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 18:18