Muh*_*uhd 1 python string time datetime string-conversion
鉴于我从一个字符串开始,比如'3/6/2011'月/日/年,当天是2011年3月13日(7天后),我如何找到自那时起已过去的年数(7/365 = 0.0191780821917808)在Python?
请注意,我希望能够处理任何输入日期.不过没有任何格式,您可以采用上面的格式.
你可以timedelta减去两个datetimes,这为你提供了许多很酷的方法来操作时差.
>>> 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
Run Code Online (Sandbox Code Playgroud)
编辑:哇,谁会认为这个简单的问题有这么多的深度.看看上得票最多的回答这个问题.处理闰年是一个"困难"的问题.(感谢@kriegar)