在大于输入日期时间的numpy数组中找到这些条目

时间:2019-01-18 20:44:28

标签: python numpy

我想找回一个datetime numpy数组的条目,该条目要比我输入的datetime变量大。

不幸的是,执行以下代码时出现此错误:

TypeError: '>' not supported between instances of 'int' and 'datetime.datetime'

这是我的代码:

import numpy as np
import pandas as pd
myRange = pd.date_range('2018-04-09', periods=5, freq='1D20min')

myArray = np.array(myRange).astype(np.datetime64).reshape(-1,1)
print("myArray:", myArray)
myDatetime = pd.datetime(2018,4,10,2,59,59)

myArray[myArray>myDatetime]

myArray: [['2018-04-09T00:00:00.000000000']
 ['2018-04-10T00:20:00.000000000']
 ['2018-04-11T00:40:00.000000000']
 ['2018-04-12T01:00:00.000000000']
 ['2018-04-13T01:20:00.000000000']]

1 个答案:

答案 0 :(得分:1)

问题在于比较:
带有
的myArray(类型为np.datetime64) myDateTime(类型为pd.datetime)

将myDateTime更改为numpy datetime64会得到结果。

import numpy as np
import pandas as pd
myRange = pd.date_range('2018-04-09', periods=5, freq='1D20min')

myArray = np.array(myRange).astype(np.datetime64).reshape(-1,1)
print("myArray:", myArray)
myDatetime = np.datetime64("2018-04-10T02:59:59")

myArray[myArray>myDatetime]

给予:

myArray: [['2018-04-09T00:00:00.000000000']
['2018-04-10T00:20:00.000000000']
['2018-04-11T00:40:00.000000000']
['2018-04-12T01:00:00.000000000']
['2018-04-13T01:20:00.000000000']]
Out[27]: 
array(['2018-04-11T00:40:00.000000000', 
       '2018-04-12T01:00:00.000000000',
       '2018-04-13T01:20:00.000000000'], dtype='datetime64[ns]')