借用自日期时间、时间戳和 datetime64 之间的转换 https://stackoverflow.com/questions/13703720/converting-between-datetime-timestamp-and-datetime64
In [220]: x
Out[220]: numpy.datetime64('2012-06-17T23:00:05.453000000-0700')
In [221]: datetime.datetime.utcfromtimestamp(x.tolist()/1e9)
Out[221]: datetime.datetime(2012, 6, 18, 6, 0, 5, 452999)
考虑到时区,我认为这是正确的。虽然看起来相当笨重。
Using int()
is 更明确(我认为)比tolist())
:
In [294]: datetime.datetime.utcfromtimestamp(int(x)/1e9)
Out[294]: datetime.datetime(2012, 6, 18, 6, 0, 5, 452999)
或获取本地日期时间:
In [295]: datetime.datetime.fromtimestamp(x.astype('O')/1e9)
但在test_datetime.py
file
https://github.com/numpy/numpy/blob/master/numpy/core/tests/test_datetime.py https://github.com/numpy/numpy/blob/master/numpy/core/tests/test_datetime.py
我找到了一些其他选项 - 首先转换一般datetime64
指定单位的格式之一:
In [296]: x.astype('M8[D]').astype('O')
Out[296]: datetime.date(2012, 6, 18)
In [297]: x.astype('M8[ms]').astype('O')
Out[297]: datetime.datetime(2012, 6, 18, 6, 0, 5, 453000)
这适用于数组:
In [303]: np.array([[x,x],[x,x]],dtype='M8[ms]').astype('O')[0,1]
Out[303]: datetime.datetime(2012, 6, 18, 6, 0, 5, 453000)