python - 为什么 numpy 数组不能从 datetime 隐式转换为 np.datetime64?

标签 python datetime numpy

比如说,我有一个datetime:

given_time = datetime(2013, 10, 8, 0, 0, 33, 945109,
                      tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=60, 
                                                             name=None))

我想把它转换成np.datetime64:

np.datetime64(given_time)
> numpy.datetime64('2013-10-08T00:00:33.945109+0100')

效果很好。但是,如果我有一个 given_time 数组:

given_times = np.array([given_time]*3) # dtype is object

given_times.astype('datetime64')given_times = np.array([given_time] * 3, dtype=np.datetime64) 都会触发 TypeError:无法根据规则“same_kind”将 datetime.datetime 对象从元数据 [us] 转换为 [D]

所以,我必须指定单位:

given_times.astype('datetime64[us]')
# or
given_times = np.array([given_time]*3, dtype='datetime64[us]')

我的问题是,为什么我必须在这里指定单位?它不需要 np.datatime64 构造函数中的单位。

最佳答案

我知道这是一个老问题,但我会尽量回答以防其他人遇到这个问题。

  1. 自 1.11 起,numpy 不会尝试自动将日期/日期时间对象的可迭代对象转换为 datetime64 数组,这从 this excerpt 中可以清楚地看出。在测试套件中:
# at the moment, we don't automatically convert these to datetime64

dt = datetime.date(1970, 1, 1)
arr = np.array([dt])
assert_equal(arr.dtype, np.dtype('O'))

dt = datetime.datetime(1970, 1, 1, 12, 30, 40)     
arr = np.array([dt])
assert_equal(arr.dtype, np.dtype('O'))

理想情况下,numpy 会认为可以使用具有正确单位的 datetime64;见this问题。

  1. 从标量构造 datetime64 时,它为日期对象设置为 M8[D] 的单位和为 M8[us]a relevant test) 的

  2. 当您指定 dtype='datetime64' 或类似地 dtype='M8' 时,单位将设置为“generic”,稍后解析为 M8[D](尽管将其解析为 M8[D] 是合乎逻辑的,请参阅 this 问题):

>>> np.datetime_data(np.dtype('datetime64'))
('generic', 1)
>>> np.datetime_data(np.dtype('M8'))
('generic', 1)
>>> np.datetime_data(np.dtype('M8[D]'))
('D', 1)
>>> np.datetime_data(np.dtype('M8[us]'))
('us', 1)
  1. given_times.astype('datetime64') 不再引发异常 - 这是 fixed在 1.11 中。

  2. 从 1.11 开始,datetime64 个对象 are timezone-naive ,因此像在提供的示例中那样传递设置了 tzinfo 的日期时间对象将触发弃用警告。

关于python - 为什么 numpy 数组不能从 datetime 隐式转换为 np.datetime64?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21988714/

相关文章:

python - 即时从 python 中的 subprocess.run() 获取输出

python - 在文档字符串中写入 "a or b"类型提示的_正确_方式是什么?

python - Pandas 无法识别 csv 文件中的日期时间索引

c# - TryParseExact 不适用于具有日期和时间的字符串,而格式仅包含日期格式

python - pymssql 抛出 ImportError : No module named _mssql when build app with py2exe

java - SmartGWT 时区

python - 将 numpy unicode 数组写入文本文件

python - 将python列表复制到numpy数组时,如何防止TypeError : list indices must be integers, not tuple?

arrays - 如何计算每次遇到零时重置的累积和

python - Matplotlib 和 :RuntimeError: main thread is not in main loop: