将 numba jitclass 中的 numpy datetime64 转换为 unix 时间戳

问题描述 投票:0回答:1

为了可读性,我希望能够向 numba jitclass 提供 numpy.datetime64 对象,该对象在类本身内转换为浮点格式的 unix 纪元时间戳。

我目前必须在创建 jitclass 对象之前计算 unix 时间戳并将其作为参数提供,例如:

>>> import numpy as np
>>> (np.datetime64('2024-01-01T00:00:00') - np.datetime64('1970-01-01T00:00:00')) / np.timedelta64(1, 's')
1704067200.0

假设我创建以下 jitclass,它采用 numpy 日期时间作为参数,如何在类中创建一个将日期时间转换为 unix 时间戳的方法?最终目标是在创建 jitclass 对象时提供开始和结束日期,然后将其转换为 unix 时间戳,以便使用

np.arange()
创建时间戳数组。

import numpy as np
from numba.experimental import jitclass
from numba import types

spec=[
    ('start', types.NPDatetime('s'))
]

@jitclass(spec)
class Foo():

    def __init__(self, start):
        self.start = start

obj = Foo(np.datetime64('2024-01-01T00:00:00'))
>>> obj.start
numpy.datetime64('2024-01-01T00:00:00')
python numba
1个回答
0
投票

IIUC,您想在

to_timestamp()
类中创建类似
Foo
方法的内容:

import numba as nb
import numpy as np

spec = [("start", nb.types.NPDatetime("s"))]

_unix_timestamp_begin = np.datetime64("1970-01-01T00:00:00")
_one_second = np.timedelta64(1, "s")


@nb.experimental.jitclass(spec)
class Foo:
    def __init__(self, start):
        self.start = start

    def to_timestamp(self):
        return (self.start - _unix_timestamp_begin) / _one_second


obj = Foo(np.datetime64("2024-01-01T00:00:00"))
print(obj.to_timestamp())

打印:

1704067200.0
© www.soinside.com 2019 - 2024. All rights reserved.