【问题标题】:Why cannot numpy arrays convert from datetime to np.datetime64 implicitly?为什么 numpy 数组不能从 datetime 隐式转换为 np.datetime64?
【发布时间】:2014-03-26 04:07:29
【问题描述】:

说,我有一个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: 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]')

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

【问题讨论】:

  • 因为 numpy 数组是变量的同质集合。 array.array也是如此。
  • @GamesBrainiac 我在问为什么 numpy 在这种情况下不能推断出单位,就像它在这里的工作方式一样:np.array(['2007-07-13', '2006-01-13', '2010-08-13'], dtype='datetime64')
  • 好问题。 np.array(np.datetime64(d) for d in [given_time] * 3) 会发生什么?
  • @uʍopǝpısdn np.array(list(np.datetime64(d) for d in [given_time] * 3)) 工作

标签: python datetime numpy


【解决方案1】:

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

  1. 从 1.11 开始,numpy 不会尝试将 date/datetime 对象的可迭代对象自动转换为 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. 1234563 @,见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') 不再引发异常——这是 1.11 中的 fixed

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    相关资源
    最近更新 更多