使用Jinja2,我如何格式化一个日期字段?我知道在Python中我可以简单地这样做:
print(car.date_of_manufacture.strftime('%Y-%m-%d'))
但是如何在Jinja2中格式化日期呢?
使用Jinja2,我如何格式化一个日期字段?我知道在Python中我可以简单地这样做:
print(car.date_of_manufacture.strftime('%Y-%m-%d'))
但是如何在Jinja2中格式化日期呢?
当前回答
在烧瓶里,用巴别塔,我喜欢这样做:
@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'))
在模板中使用{{mydatetimeobject|dt}}
使用Babel,你可以在消息中指定不同的格式。比如Po是这样的:
#: app/views.py:36
#, python-format
msgid "%%m/%%d/%%Y"
msgstr "%%d/%%m/%%Y"
其他回答
我认为你必须自己编写筛选器。它实际上是文档中自定义过滤器的示例:http://jinja.pocoo.org/docs/api/#custom-filters
你可以在没有任何过滤器的模板中这样使用它
{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}
有一个jinja2扩展你可以使用只需要pip安装(https://github.com/hackebrot/jinja2-time)
如果您正在处理较低级别的时间对象(我通常只使用整数),并且出于某种原因不想编写自定义过滤器,那么我使用的一种方法是将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))
然后可以在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>
你可以像这样在jinja模板中使用它 {{row.session_start_date_time。strftime(“% d - Y % m - % % H: % m: % S ')}}
在这段代码中,字段名是row.session_start_date_time。