Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

converting numpy datetime64 in a numba jitclass to unix timestamp

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading