pybind11 icon indicating copy to clipboard operation
pybind11 copied to clipboard

I am not able to get uint64_t* for np.datetime64

Open vasica38 opened this issue 6 years ago • 1 comments

the error: "cannot convert value dtype('<M8[ns]') to dtype(uint64t)"

code example:

auto arr_value = py::cast<py::array_t<std::uint64_t, py::array::c_style>>(df["datetime_column].attr("to_numpy")());
std::uint64_t* pointer = static_cast<std::uint64_t*>(arr_value);

vasica38 avatar Oct 28 '19 17:10 vasica38


#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <iostream>

namespace py = pybind11;

void process_datetime_column(const py::object& df) {
    // Extract the 'datetime_column' and convert to numpy array
    py::array arr_value = df.attr("datetime_column").attr("to_numpy")();

    // View the numpy array as uint64_t, which is the number of nanoseconds since the Unix epoch
    py::array_t<std::uint64_t> arr_uint64 = arr_value.attr("view")(py::dtype::of<std::uint64_t>());
    
    // Get pointer to the underlying data
    std::uint64_t* pointer = arr_uint64.mutable_data();

    // Print the first few values
    for (ssize_t i = 0; i < 5; ++i) {
        std::cout << "Value " << i << ": " << pointer[i] << std::endl;
    }
}

PYBIND11_MODULE(datetime_conversion, m) {
    m.def("process_datetime_column", &process_datetime_column, "Process the datetime column and convert it to uint64_t");
}

ljluestc avatar Dec 24 '24 23:12 ljluestc