优雅地将 int64 的 numpy 数组转换为 datetime64 的 numpy 数组

dsh*_*hin 4 python numpy python-3.x

我有一个代表纳秒x的 dtype numpy 数组np.int64。我可以np.datetime64使用以下代码将其转换为 dtype 的 numpy 数组:

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

有没有更好的方法来做到这一点,避免 python 列表理解?

Qua*_*ang 5

你可以做:

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

x.astype('datetime64[ns]')
Run Code Online (Sandbox Code Playgroud)

输出:

array(['1970-01-01T00:00:01.000000000', '1970-01-01T00:00:05.000000000',
       '1970-01-01T00:00:10.000000000'], dtype='datetime64[ns]')
Run Code Online (Sandbox Code Playgroud)