首页 > 解决方案 > Length of a datetimeindex in python

问题描述

I just cant find the answer and I know pandas eats problems like this for desert.

I have a datetime index and want to know its length, in years:

idx=pd.date_range('2011-07-03', '2015-07-10')

expected output:

4.0191 years   (4 years and 7 days)

If I do: idx[0]-idx[-1] I get an output in days, but id like it in years

Sorry: couldn't locate on panads docs

标签: pythonpandasdatetimetimedeltadatetimeindex

解决方案


You can convert timedelta to days and then divide by 365.25 if is not necessary 100% accuracy:

idx=pd.date_range('2011-07-03', '2015-07-10')

print ((idx[-1]-idx[0]).days / 365.25)

4.0191649555099245

But if need years with days:

from dateutil.relativedelta import relativedelta

r = relativedelta(idx[-1], idx[0])
print('{} years {} days'.format(r.years, r.days))
4 years 7 days

推荐阅读