2014-01-20 84 views
0

如何获取两个日期的差异并输出类似1 Year 3 months的内容?获取日期差异和输出:年份 - 月份

我正在使用Jinja2模板引擎。目前我有:

{{ context.job_history|map(attribute="to_")|first - context.job_history|map(attribute="from_")|first }} 

,输出:

370天

我曾尝试:

{{ (context.job_history|map(attribute="to_")|first - context.job_history|map(attribute="from_")|first)/365 }} 

但是,这给了我一个TypeError

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

我认为(个人认为)Jinja2语法接近于python语法。

回答

1

使用.days属性返回datetime.timedelta对象:

{{ (context.job_history|map(attribute="to_")|first - context.job_history|map(attribute="from_")|first).days/365 }} 

,但你真的想建立在你的Python代码查看这些信息。

+0

这解决了'TypeError',谢谢,但是我如何得到'1年3个月'的输出? – Renier

+1

@Renier你真的应该写你自己的格式化程序。在模板中指定它不仅非常困难,而且非常容易混淆。 – poke

+1

@Renier:真的,在Python代码中执行此操作。那么你可以使用'divmod(td,365)'得到几年和剩余的天数,然后使用另一个'divmod(余数,30)'来获得几个月。不要在模板代码中执行此操作。 –

相关问题