我正在尝试格式化使用datetime.datetime.utcnow()
生成的日期(使用它,因为它相当于我的应用程序使用的MongoDB中的ISODate()
)我的Flask应用程序但是Jinja2不会渲染它们。
我的应用程序中有以下功能:
def format_isodate(timestamp):
"""Format a ISODate time stamp for display."""
date = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S.%f")
return date.strftime('%Y-%m-%d @ %H:%M:%S')
日期如下:
"2013-07-04 20:06:05.088000"
我有以下过滤器:
app.jinja_env.filters['isodateformat'] = format_isodate
但是当我尝试格式化模板中的时间戳时:
{{ change.submit_date|isodateformat }}
我收到此错误:
“TypeError:必须是字符串,而不是datetime.datetime”
我不明白为什么我会收到此错误。 strftime()
不将日期转换为字符串吗?
答案 0 :(得分:4)
问题是utcnow()
返回datetime.datetime
个对象,而不是字符串。如果检查异常中的行号,则可能是strptime
调用失败 - 它可以将字符串解析为日期,但它无法解析日期。
示例:
#!/usr/bin/env python2.7
import datetime
import jinja2
def format_isodate(timestamp):
"""Format a ISODate time stamp for display."""
date = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S.%f")
return date.strftime('%Y-%m-%d @ %H:%M:%S')
e = jinja2.Environment()
e.filters['isodateformat'] = format_isodate
t = e.from_string('{{ change.submit_date|isodateformat }}')
print t.render(change={'submit_date': "2013-07-04 20:06:05.088000"})
print t.render(change={'submit_date': datetime.datetime.now()})
字符串的第一个打印成功,但第二个打印失败并显示TypeError: must be string, not datetime.datetime
。