1

For the sake of readability I want to be able to supply a numpy.datetime64 object to a numba jitclass which is converted to a unix epoch timestamp in float format within the class itself.

I currently have to resort to calculating the unix timestamp prior to creating the jitclass object and supply this as a parameter, e.g.:

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

Suppose that I create the following jitclass that takes a numpy datetime as parameter, how can I create a method within the class that converts the datetime into a unix timestamp? The ultimate goal would be to supply a start and end date when creating the jitclass object, which are then converted to unix timestamps in order to create an array of timestamps using 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')

1 Answer 1

1

IIUC, you want to create something like to_timestamp() method in the Foo class:

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())

Prints:

1704067200.0
Sign up to request clarification or add additional context in comments.

1 Comment

That indeed seems to do the trick. I was under the impression that jitclasses couldn't handle global variables but this seems to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.