【问题标题】:How to format a jinja2 date of type String如何格式化字符串类型的 jinja2 日期
【发布时间】:2021-05-02 16:25:54
【问题描述】:

我在我的 yml 文件中收到一个 Json,然后它转到我的 jinja2 html 文件。 我可以在不修改的情况下使用我的数据,但是当我尝试过滤器或任何格式化我的日期时它失败了。

像这样它可以在不格式化日期的情况下工作:

<p>{{rule.occurences[0]}}</p>

结果:

2021-01-28T09:40:10.970Z

我希望它是这样的:

2021-01-28

我试着用这个来格式化我的日期:

<p>{{rule.occurences[0].strftime('%Y-%m-%d')}}</p>

结果:

ERROR     -- [TaskProcess] 'str object' has no attribute 'strftime'

我还尝试了自定义过滤器:

<p>{{rule.occurences[0]|datetimeformat('%d-%m-%Y')}}</p>

结果:

ERROR     -- [TaskProcess] datetimeformat() takes 1 positional argument but 2 were given

也试过这个:

<p>{{rule.occurences[0]|iso8601_to_time|datetimeformat('%d-%m-%Y')}}</p>

结果:

ERROR     -- [load_file] Couldn't load file jinja2: no filter named 'iso8601_to_time'

有什么办法解决这个问题吗?

【问题讨论】:

    标签: python html date yaml jinja2


    【解决方案1】:
    import datetime
    a='2021-01-28T09:40:10.970'
    datetime.datetime.strptime(a[:10],'%Y-%m-%d').strftime('%Y-%m-%d')
    

    输出:

    '2021-01-28'
    

    【讨论】:

    • 谢谢你的回答,我终于做到了:{{rule.occurences[0]|truncate(10, True, '', 0)}}
    猜你喜欢
    • 2011-06-17
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2022-10-13
    • 2011-02-25
    • 1970-01-01
    相关资源
    最近更新 更多