Elegantly convert a numpy array of int64 to a numpy array of datetime64

Question:

I have a numpy array x of dtype np.int64 representing nanoseconds. I’m able to convert this into a numpy array of dtype np.datetime64 with the following code:

np.array([np.datetime64(int(a), 'ns') for a in x])

Is there a better way to do this, that avoids python list comprehension?

Asked By: dshin

||

Answers:

You can do:

x = np.array([1e9, 5e9, 1e10], dtype=np.int64)

x.astype('datetime64[ns]')

Output:

array(['1970-01-01T00:00:01.000000000', '1970-01-01T00:00:05.000000000',
       '1970-01-01T00:00:10.000000000'], dtype='datetime64[ns]')
Answered By: Quang Hoang
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.