Python 我如何在 Jinja2 中格式化日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4830535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:43:05  来源:igfitidea点击:

How do I format a date in Jinja2?

pythonjinja2

提问by Ambrosio

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

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

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

But how do I format the date in Jinja2?

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

采纳答案by tux21b

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

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

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

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

{{ car.date_of_manufacture|datetime }}
{{ car.date_of_manufacture|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_timedeltafor that, and register it as filter similar to the datetime example given here.

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

回答by Brian Goldman

I think you have to write your own filter for that. It's actually the example for custom filters in the documentation: http://jinja.pocoo.org/docs/api/#custom-filters

我认为您必须为此编写自己的过滤器。它实际上是文档中自定义过滤器的示例:http: //jinja.pocoo.org/docs/api/#custom-filters

回答by Raj

Here's the filter that I ended up using for strftime in Jinja2 and Flask

这是我最终在 Jinja2 和 Flask 中用于 strftime 的过滤器

@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) 

And then you use the filter like so:

然后你像这样使用过滤器:

{{car.date_of_manufacture|strftime}}

回答by Andrew Murphy

Google App Engine users : If you're moving from Django to Jinja2, and looking to replace the date filter, note that the % formatting codes are different.

Google App Engine 用户:如果您要从 Django 迁移到 Jinja2,并希望替换日期过滤器,请注意 % 格式代码是不同的。

The strftime % codes are here: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

strftime % 代码在这里:http: //docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

回答by Olly F-G

If you are dealing with a lower level time object (I often just use integers), and don't want to write a custom filter for whatever reason, an approach I use is to pass the strftime function into the template as a variable, where it can be called where you need it.

如果您正在处理较低级别的时间对象(我通常只使用整数),并且出于任何原因不想编写自定义过滤器,我使用的方法是将 strftime 函数作为变量传递到模板中,其中它可以在您需要的地方调用。

For example:

例如:

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))

Which can then be used within sometemplate.html:

然后可以在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>

回答by euri10

in flask, with babel, I like to do this :

在烧瓶中,使用 babel,我喜欢这样做:

@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'))

used in the template with {{mydatetimeobject|dt}}

在模板中使用 {{mydatetimeobject|dt}}

so no with babel you can specify your various format in messages.po like this for instance :

所以没有 babel 你可以在 messages.po 中指定你的各种格式,例如:

#: app/views.py:36
#, python-format
msgid "%%m/%%d/%%Y"
msgstr "%%d/%%m/%%Y"

回答by Zaytsev Dmitry

You can use it like this in template without any filters

您可以像这样在模板中使用它而无需任何过滤器

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

回答by mumubin

There is a jinja2 extension you can use just need pip install (https://github.com/hackebrot/jinja2-tim)

有一个 jinja2 扩展你可以使用只需要 pip install ( https://github.com/hackebrot/jinja2-tim)