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

Amb*_*sio 169 python jinja2

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

print(car.date_of_manufacture.strftime('%Y-%m-%d'))
Run Code Online (Sandbox Code Playgroud)

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

tux*_*21b 301

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

{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}
Run Code Online (Sandbox Code Playgroud)

另一个更好的方法是定义自己的过滤器,例如:

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
Run Code Online (Sandbox Code Playgroud)

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

{{ car.date_of_manufacture|datetime }}
{{ car.date_of_manufacture|datetime('full') }}
Run Code Online (Sandbox Code Playgroud)

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

  • 根据你的问题,你在谈论不同的事情.初始,这个线程是关于从python模块`datetime`格式化`datetime`对象,但是你试图从低级`time`模块格式化`struct_time`对象.`struct_time`对象没有`strftime()`方法,尽管时间包中可能有一个全局的`strftime()`方法.但我建议你使用高级(平台无关)`datetime`包. (7认同)
  • @StefanNch"定义一个新的过滤器,在任何方面都不是更好".它可以是:如果在模板中多次调用过滤器,这可以避免重复格式字符串,并且可以导致写入更少的代码.更重要的是,通过添加abstration来减少*重复*代码. (3认同)
  • 你真的试过吗?直接调用它会导致:'time.struct_time object'没有属性'strftime' (2认同)
  • 我认为你的意思是'babel.dates.format_datetime(value,format)` (2认同)
  • 定义一个新的过滤器,在任何方面都不是更好.要编写更多代码=要维护的代码更多=要解析的更多代码,更多代码缓存(如果使用)和解释.使用Jinja2的一大优势是能够在模板中编写小python代码.与Django的模板系统相比,一些性能提升来自于此. (2认同)

Raj*_*Raj 20

这是我最终在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) 
Run Code Online (Sandbox Code Playgroud)

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

{{car.date_of_manufacture|strftime}}
Run Code Online (Sandbox Code Playgroud)

  • 为什么`dateutil`和`native`? (2认同)

Bri*_*man 16

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


Oll*_*F-G 14

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

例如:

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))
Run Code Online (Sandbox Code Playgroud)

然后可以在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>
Run Code Online (Sandbox Code Playgroud)


And*_*phy 5

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

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


Zay*_*try 5

您可以在没有任何过滤器的模板中像这样使用它

{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以在 jinja 模板中像这样使用它 {{ row.session_start_date_time.strftime('%d-%m-%Y %H:%M:%S')}}

在此代码中,字段名称为row.session_start_date_time.