我正在尝试格式化使用 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: must be string, not datetime.datetime"
我不明白为什么会出现此错误。 strftime()
不会将日期转换为字符串吗?
最佳答案
问题是 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
。
关于python - 使用 strftime 时 Jinja2 模板中的 "TypeError: must be string, not datetime.datetime",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17478391/