Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 720
dshin Avatar asked Sep 09 '25 14:09

dshin


1 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]')
like image 71
Quang Hoang Avatar answered Sep 12 '25 03:09

Quang Hoang