python - 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
解决方案
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 year
s with day
s:
from dateutil.relativedelta import relativedelta
r = relativedelta(idx[-1], idx[0])
print('{} years {} days'.format(r.years, r.days))
4 years 7 days
推荐阅读
- django - Django:如何将数据保存到 ManyToManyField
- php - 从私有 API 读取数据
- java - Java:定义为全局变量时处理 IOException
- mysql - MySQL注入绕过点(。)和逗号(,)
- c++ - cpp 没有匹配的函数调用来调用构造函数。为什么?
- siddhi - 我们可以使用 REST api 作为 Siddhi 事件表的数据源吗?
- c++ - CMake 标头仅依赖项
- go - 如何在 Golang 中使用 gobuffalo/packr
- python - 确定没有扩展名的文件的文件类型
- python - 根据以前的任务为 5 个 python 脚本创建管道