【问题标题】:How to get index of datetime within a pandas DateTimeIndex?如何在熊猫 DateTimeIndex 中获取日期时间索引?
【发布时间】:2019-03-28 23:48:52
【问题描述】:

有没有办法在DateTimeIndex中直接获取某个datetime的索引?

在将DateTimeIndex 转换为list 后,我有以下玩具示例代码可以执行我想要的操作。

import pandas as pd
import datetime

year = 2020
minutesStep = 10
dateTimeStr = "2020-01-01 00:40:00"

datesTimes = pd.date_range(start='1/1/'+str(year), end='1/1/'+str(year+1), freq=str(minutesStep)+'min')
dateTimeObj = datetime.datetime.strptime(dateTimeStr, '%Y-%m-%d %H:%M:%S')

l = datesTimes.tolist()
i = l.index(dateTimeObj)
print i
print datesTimes[i]

这会输出预期的结果:

>>> 
4
2020-01-01 00:40:00

但是我想直接从DateTimeIndex 获取索引。这可能吗?

【问题讨论】:

    标签: python pandas datetimeindex


    【解决方案1】:

    使用get_loc 函数可以在pandas DateTimeIndex 中获取特定datetime 的索引,如下所示:

    j = datesTimes.get_loc(dateTimeObj)
    print j
    print datesTimes[j]
    

    哪些输出以及预期的输出:

    >>> 
    4
    2020-01-01 00:40:00
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 2022-08-07
      • 2018-07-04
      • 1970-01-01
      相关资源
      最近更新 更多