将NumPy对象数组转换为datetime64

时间:2017-09-19 07:53:01

标签: python arrays numpy datetime type-conversion

data['RealTime'][:,0]
Out[23]: 
array([datetime.datetime(2017, 9, 12, 18, 13, 8, 826000),
       datetime.datetime(2017, 9, 12, 18, 13, 8, 846000),
       datetime.datetime(2017, 9, 12, 18, 13, 8, 866000), ...,
       datetime.datetime(2017, 9, 12, 18, 30, 40, 186000),
       datetime.datetime(2017, 9, 12, 18, 30, 40, 206000),
       datetime.datetime(2017, 9, 12, 18, 30, 40, 226000)], dtype=object)

如何转换为dtype datetime数组?

1 个答案:

答案 0 :(得分:1)

我知道你有pandas,所以你可以使用pd.to_datetime

out = pd.to_datetime(array)
print(out)

DatetimeIndex(['2017-09-12 18:13:08.826000', '2017-09-12 18:13:08.846000',
               '2017-09-12 18:13:08.866000', '2017-09-12 18:30:40.186000',
               '2017-09-12 18:30:40.206000', '2017-09-12 18:30:40.226000'],
              dtype='datetime64[ns]', freq=None)

您可以通过访问numpyout检索out.values数组。

使用numpy,您可以使用astype执行相同的操作:

out = array.astype("datetime64[ns]")
print(out)

array(['2017-09-12T18:13:08.826000000', '2017-09-12T18:13:08.846000000',
       '2017-09-12T18:13:08.866000000', '2017-09-12T18:30:40.186000000',
       '2017-09-12T18:30:40.206000000', '2017-09-12T18:30:40.226000000'], dtype='datetime64[ns]')