开发者社区 问答 正文

tornado 模板中如何使用datetime.datime.strptime函数?报错

大家好,今天遇到一个问题!

就是在tornado模板中需要转换日期字符串的格式!

例如,收到的字符串是'2015-10-11',我需要转换成'Oct 11, 2015'

我用的是strptime和strftime两个函数!

具体如下:

datetime.datetime.strptime('2015-10-11', "%Y-%m-%d").strftime("%b %d, %Y")



在tornado模板我看到datetime关键字是指的是python中的datatime模块,然后我在tornado模板中写了这么一句代码:

<time class="entry-date">{{ datetime.datetime.strptime(passage.mtime, "%Y-%m-%d ").strptime("%b %d, %Y") }}</time>



然后运行的时候程序就报错了,错误提示如下所示:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/tornado-4.3.dev1-py2.7-linux-x86_64.egg/tornado/web.py", line 1411, in _execute
    result = method(*self.path_args, **self.path_kwargs)
  File "./blog.py", line 87, in get
    self.render("index.html", aside=True, passages=passages)
  File "/usr/local/lib/python2.7/dist-packages/tornado-4.3.dev1-py2.7-linux-x86_64.egg/tornado/web.py", line 701, in render
    html = self.render_string(template_name, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tornado-4.3.dev1-py2.7-linux-x86_64.egg/tornado/web.py", line 808, in render_string
    return t.generate(**namespace)
  File "/usr/local/lib/python2.7/dist-packages/tornado-4.3.dev1-py2.7-linux-x86_64.egg/tornado/template.py", line 345, in generate
    return execute()
  File "index_html.generated.py", line 82, in _tt_execute
    _tt_tmp = datetime.datetime.strptime(passage.mtime, "%Y-%m-%d %H:%M:%S").strptime("%b %d, %Y")  # index.html:16 (via base.html:56)
TypeError: must be string, not datetime.datetime



我个人分析,感觉是tornado中将datetime关键字解析了两次(datetime.datetime.strptime语句中),请问一下这个该怎么解决啊?

展开
收起
爱吃鱼的程序员 2020-06-12 10:47:39 810 分享 版权
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    好吧,解决了,我穿过来的参数我以为是个字符串,结果是个datetime.datetime类型!

    变成这样就好啦

    <timeclass="entry-date">{{passage.mtime.strftime("%b%d,%Y")}}</time>



    折腾了两个小时,原来是把参数类型当错了!

    传进来的是SQL中的datetime,我当成字符串了,坑爹啊!

    可以在模版中引入python模块儿:{%includedatetime%}恩,了解了!不过这个问题已经解决了!是我看错出入参数的类型了!datetime当成string来用了!
    2020-06-12 10:47:56
    赞同 展开评论
问答分类:
问答地址: