import numpy
a = numpy.array([20090913, 20101020, 20110125])
你能解释一下为什么 numpy.datetime64(a.astype("S8").tolist())
可以正确转换,但 numpy.datetime64(a.astype("S8") 不能转换)
?为什么 numpy 函数不接受 numpy 字符串而只接受常规 python 字符串?我正在使用 Numpy 1.6.1 和 Python 2.7.2 Windows 7。
最佳答案
重现您的结果:
>>> a = numpy.array([20090913, 20101020, 20110125])
>>> numpy.datetime64(a.astype("S8").tolist())
array([2009-09-13 00:00:00, 2010-10-20 00:00:00, 2011-01-25 00:00:00], dtype=datetime64[us])
>>> numpy.datetime64(a.astype("S8"))
array([1970-01-01 00:00:20.090913, 1970-01-01 00:00:20.101020,
1970-01-01 00:00:20.110125], dtype=datetime64[us])
关键是:
>>> a.astype("S8").tolist()
['20090913', '20101020', '20110125']
>>> a.astype("S8")
array(['20090913', '20101020', '20110125'],
dtype='|S8')
在第一种情况下,字符串参数被传递到 numpy.datetime64 并被正确解析,正如您所描述的那样。在第二个中,它需要根据推测从 |S8
执行显式强制转换。事实证明这是正在考虑的,但目前explicitly isn't supported :
This didn't go in, because the datetime properties don't exist on the arrays after you convert them to datetime64, so there could be some unintuitive consequences from that. When Martin implemented the quaternion dtype, we discussed the possibility that dtypes could expose properties that show up on the array object, and if this were implemented I think the conversion and compatibility between python datetime and datetime64 could be made quite natural.
The documentation有更多您可能希望考虑的工作强制示例,包括来自其他 numpy 时间格式的示例。如果您认为显式类型强制的需要是错误的,我建议将其报告给 numpy 团队,并且如果可能的话,提交您自己的补丁。
关于python - Numpy 奇怪行为转换为 datetime64 dtype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9709824/