gabboshow
gabboshow

Reputation: 5549

Convert NumPy object array to datetime64

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)

how can I convert into an array of dtype datetime?

Upvotes: 0

Views: 7580

Answers (1)

cs95
cs95

Reputation: 402263

I know you have pandas, so you can just use 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)

You can retrieve a numpy array from out by accessing out.values.


With numpy, you'd do the same thing using 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]')

Upvotes: 3

Related Questions