python - Numpy 奇怪行为转换为 datetime64 dtype

标签 python datetime numpy

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/

相关文章:

Python 漂亮的汤参数

laravel - 使用 Carbon 更改时区

c# - DateTime.Today ,一天的开始还是结束?

python - 带有 OMP : can't import module, undefined symbol GOMP_* 的 f2py

python - 在没有显式循环的情况下构建具有多个自定义索引范围的 numpy 数组

python - 在 Azure 上运行 .exe

python - 序列化Haystack SearchQuerySet

python - 将多类数组投影为二进制矩阵

python - 从 scrapy 导出 csv 文件(不是通过命令行)

mysql select between two dates 有奇怪的行为