【问题标题】:How do I perform arithmetic operation on a templated type using Jinja2?如何使用 Jinja2 对模板类型执行算术运算?
【发布时间】:2023-01-11 04:06:42
【问题描述】:

我正在尝试使用 Jinja2 对模板化的 datetime 值执行算术运算。我查看了以下问题:Perform arithmetic operation in Jinja2,我发现 Jinja2 支持对模板类型执行算术运算。
我想将其扩展到datetime

我试过这样做:

from jinja2 import Template
import datetime
template = Template("Date: {{ currentDate +2  }}")
template.render(currentDate=datetime.datetime.today())

但它抛出以下内容:

TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'int'

我尝试考虑一个解决方案,我可以在其中分配一个函数,该函数在调用时返回自纪元以来的天数,但我仍然需要能够将该值表示为有效日期。
我如何使用 Jinja2 实现此目的?

【问题讨论】:

  • 那么你也不能在 Python 中做到这一点,now+2 甚至意味着什么?从现在开始是两秒、几分钟、几天、几个月还是几年?
  • 是天数。

标签: python-3.x jinja2


【解决方案1】:

由于您的目标是将两天添加到另一个日期,您可以将 datetime 模块传递给模板,然后使用它的 timedelta() 方法:

鉴于:

from jinja2 import Template
import datetime

template = Template("""
Date:        {{ currentDate }}
In two days: {{ currentDate + datetime.timedelta(days=2) }}
""")
print(
    template.render(
        currentDate=datetime.datetime.today(), 
        datetime=datetime
    )
)

这将产生:

Date:        2023-01-10 19:52:50.276999
In two days: 2023-01-12 19:52:50.276999

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-03
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多