如何使用C API创建datetime64对象的Numpy数组?

2 投票
1 回答
1131 浏览
提问于 2025-04-18 15:18

我需要在C/C++代码中创建一个包含numpy的datetime64对象的数组。就像我对NPY_LONGLONGNPY_VOID所做的那样,我也需要对NPY_DATETIME类型做同样的事情。

PyObject *arr1 = PyArray_SimpleNew(1, &dims, NPY_LONGLONG);
PyObject *arr2 = PyArray_New(&PyArray_Type, 1, &dims, NPY_VOID, NULL, NULL, item_size, 0, NULL);

问题是,关于NPY_DATETIME类型的内部表示没有任何文档,所以我不知道它是否有固定的大小或结构。

如果你能像我对NPY_LONGLONGNPY_VOID那样提供一个例子,那就太好了。

1 个回答

3

我找到了一种不错的解决方案。下面是我的一个函数,它可以从C语言的缓冲区创建一个numpy数组。

PyObject* create_datetime_array(int index, std::string const &dtype)
{
    int buffer_size = this->elements_count*sizeof(omd::OT_int64);
    npy_intp dims = this->elements_count;
    PyObject *date_type = Py_BuildValue("s", dtype.c_str());
    PyArray_Descr *descr;
    PyArray_DescrConverter(date_type, &descr);
    Py_XDECREF(date_type);
    PyObject *arr = PyArray_SimpleNewFromDescr(1, &dims, descr);
    memcpy(PyArray_BYTES((PyArrayObject *)arr), &(this->int64_data[index][0]), buffer_size);
    return arr;
}

dtype 可以是 M8[毫秒]、M8[微秒] 或 M8[纳秒]。

撰写回答