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

col*_*ang 16 python datetime numpy

说,我有一个datetime:

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

我想将其转换为np.datetime64:

np.datetime64(given_time)
> numpy.datetime64('2013-10-08T00:00:33.945109+0100')
Run Code Online (Sandbox Code Playgroud)

它运作良好.但是,如果我有一个数组given_time:

given_times = np.array([given_time]*3) # dtype is object
Run Code Online (Sandbox Code Playgroud)

双方given_times.astype('datetime64')given_times = np.array([given_time] * 3, dtype=np.datetime64)会引发TypeError: Cannot cast datetime.datetime object from metadata [us] to [D] according to the rule 'same_kind'

所以,我必须指定单位:

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

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

ald*_*nor 6

我知道这是一个老问题,但我会尝试回答以防其他人遇到这个问题.

  1. 从1.11开始,numpy不会尝试自动将date/datetime对象的iterables转换为datetime64数组,这在测试套件的这段摘录中非常清楚:
# 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'))
Run Code Online (Sandbox Code Playgroud)

理想情况下,numpy可以datetime64使用正确的单位; 看到这个问题.

  1. datetime64从标量构造时,它M8[D]为日期对象设置的单位和M8[us]日期时间对象(相关测试).

  2. 当您指定dtype='datetime64'或类似地dtype='M8'将单位设置为"generic"时,后面将解析为M8[D](虽然将其解析为合理,但M8[D]请参阅问题):

>>> 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)
Run Code Online (Sandbox Code Playgroud)
  1. given_times.astype('datetime64')不再引发异常 - 这在1.11中得到修复.

  2. 从1.11开始,datetime64对象是时区初始的,因此tzinfo在提供的示例中传递带有set 的datetime对象将触发弃用警告.