Python:获取从日期字符串中获得的年数

问题描述:

考虑到我以字符串开头,如​​(月/日/年),当前日期为2011年3月13日(7天后)我可以在Python中找到自那时以来经过的年数(7/365 = 0.0191780821917808)吗?Python:获取从日期字符串中获得的年数

请注意,我希望能够处理任何输入日期。不是任何格式,你可以假设上面的格式。

您可以通过减去两个datetime s得到timedelta,这为您提供了很多很酷的方法来处理时差。

>>> import datetime 
>>> before = datetime.datetime.strptime('3/6/2011','%m/%d/%Y') 
>>> now = datetime.datetime.now() 
>>> type(now-before) 
<type 'datetime.timedelta'> 
>>> (now-before).days 
7 
>>> float((now-before).days)/365 
0.019178082191780823 

编辑:哇,谁曾想过有这么多的深入到这个简单的问题。看看this question上票数最多的答案。处理闰年是一个“困难”的问题。 (赠送@kriegar)

+0

我再经365分(现已前).days拿到分数的一年。 – 2011-03-14 03:15:46

+1

不是闰年是这个解决方案的问题吗? – DTing 2011-03-14 03:25:23

+0

我的应用程序已经有了一些误差,所以闰年可能并不是什么大问题,因为这个误差 Muhd 2011-03-14 03:53:10

>>> import datetime 
>>> datestring = "3/6/2011" 
>>> (datetime.date.today() - datetime.datetime.strptime(datestring, "%m/%d/%Y").date()).days/365.0 
0.019178082191780823 

以上所有答案都没有考虑到闰年。看起来这个问题的讨论与你的问题有关。

Pythonic difference between two dates in years?

+1

公平地说,他确实在他的问题中提出了“x/365”答案。 – 2011-03-14 03:27:46

+0

+1,但我想说的是,使用365的分数年很腥 – DTing 2011-03-14 03:29:21

+0

极好的一点。在阅读你的链接之后,很明显,这是一个比起初看起来更难的问题 - 主要是因为我们认为“年”是对时间的非常一致的衡量,但实际上它的变量取决于你“重新谈论。 – 2011-03-14 03:38:41