【Python】numpy.datetime64时间转换为 datetime.datetime

一、说明

直接使用astype(datetime.datetime)方法,可能返回为整形

In: np.datetime64('2012-06-18T02:00:05.453000000-0400').astype(datetime.datetime)
Out: 1339999205453000000L

二、解决办法

查看numpy源码测试文件 https://github.com/numpy/numpy/blob/master/numpy/core/tests/test_datetime.py
【Python】numpy.datetime64时间转换为 datetime.datetime_第1张图片

可以尝试这样转换:

In [296]:x=np.datetime64('2012-06-18T02:00:05.453000000-0400').astype(datetime.datetime)
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)

三、源码

构建了一个pandas数组df1:
【Python】numpy.datetime64时间转换为 datetime.datetime_第2张图片
通过datetime.timedelta,遍历缺失项

dtime = datetime.datetime(2018, 6, 4, 8, 0, 0)
dtime = (df1[-2:-1])['时间'].values[0]
dtime = dtime.astype('M8[s]').astype('O')
dtime = dtime + datetime.timedelta(minutes=5)

四、参考链接:

https://stackoverflow.com/questions/29753060/how-to-convert-numpy-datetime64-into-datetime

你可能感兴趣的:(#,Python,numpy,python,数据分析)