gpt4 book ai didi

python - C API 中 Numpy datetime64 的转换

转载 作者:行者123 更新时间:2023-11-30 15:01:07 24 4
gpt4 key购买 nike

如何在 C 中使用从 Python 传递的 datetime64?我在 Numpy header 中发现了一些已弃用的函数,例如 PyArray_DatetimeToDatetimeStruct(),但找不到与 datetime64 相关的任何内容。

它看起来像是一个整数数组以及后端的一些元数据,但如果是这样,您如何确定单位?

最佳答案

对于那些想知道将来如何做到这一点的人,这是我最终得到的解决方案。

从 Python 中将 datetime64 作为 int64 传递:

dt = np.datetime64(datetime.utcnow())
my_C_func(dt.astype(np.int64))

C中的解码源自gmtime()的源码。此代码假设日期时间以微秒为单位,您可以通过检查 dtype 来确定(感谢 @hpaulj)。 start 是来自 Python 的 datetime64。

inline int
is_leapyear(uint64_t year)
{
return (year & 0x3) == 0 && /* year % 4 == 0 */
((year % 100) != 0 ||
(year % 400) == 0);
}
#define YEARSIZE(year) (is_leapyear(year) ? 366u : 365u)

...

uint64_t us_per_day = 1000ull * 1000ull * 60ull * 60ull * 24ull;
register uint64_t dayclock = start % us_per_day;
register uint64_t dayno = start / us_per_day;

uint64_t year = 1970ull;

uint64_t us = dayclock % 1000000ull;
uint64_t sec = (dayclock / 1000000ull) % 60ull;
uint64_t minute = (dayclock % 3600000000ull) / 60000000ull;
uint64_t hour = dayclock / 3600000000ull;
while (dayno >= YEARSIZE(year))
{
dayno -= YEARSIZE(year);
year++;
}

uint64_t day = dayno + 1;

如果您不需要比秒更准确的值,您可以简单地执行以下操作:

uint64_t other_start = start / 1000000ull;
struct tm* ptm;
ptm = gmtime((time_t*)&other_start);

printf("\tGMTIME VERSION:\n");
printf("\tyear: %d\n", ptm->tm_year);
printf("\tday: %d\n", ptm->tm_yday);
printf("\thours: %d\n", ptm->tm_hour);
printf("\tminutes: %d\n", ptm->tm_min);
printf("\tsec: %d\n", ptm->tm_sec);

当然美国部分可以单独获取:

uint64_t us = source % 1000000ull;

关于python - C API 中 Numpy datetime64 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41642874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com