2014-01-20 81 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)'來獲得幾個月。不要在模板代碼中執行此操作。 –

相關問題