为什么numpy在较新版本中开始将date对象转换为datetime64 [s] type对象?如何使其向后兼容?
示例:
代码段:
import datetime
import numpy as np
dt = datetime.date(1970, 1, 1)
array = np.array([dt], dtype='datetime64[s]')
array
结果:
**Numpy version 1.12.0**
array(['1970-01-01T00:00:00'], dtype='datetime64[s]')
**Numpy version 1.9.3**
TypeError: Cannot cast datetime.date object from metadata [D] to [s] according to the rule 'same_kind'
答案 0 :(得分:1)
尝试''D'中间体:
In [27]: np.array([dt],'datetime64[D]')
Out[27]: array(['1970-01-01'], dtype='datetime64[D]')
In [28]: np.array([dt],'datetime64[D]').astype('datetime64[s]')
Out[28]: array(['1970-01-01T00:00:00'], dtype='datetime64[s]')
虽然在我的版本中,直接创作有效:
In [29]: np.array([dt],'datetime64[s]')
Out[29]: array(['1970-01-01T00:00:00'], dtype='datetime64[s]')
In [30]: np.__version__
Out[30]: '1.12.0'
In [31]: dt
Out[31]: datetime.date(1970, 1, 1)