Convert datetime64 and timedelta64 to integer (in nanoseconds)

Hi all, is it possible to convert np.datetime64 and np.timedelta64 into integer within Numba?

import numpy as np
import pandas as pd
from numba import njit

@njit
def f(dt):
    return int(dt)

f(pd.Timestamp.now().to_datetime64())
TypingError: Failed in nopython mode pipeline (step: nopython frontend)
No implementation of function Function(<class 'int'>) found for signature:
 
 >>> int(datetime64[ns])
 
There are 2 candidate implementations:
  - Of which 2 did not match due to:
  Overload of function 'int': File: numba/core/typing/builtins.py: Line 925.
    With argument(s): '(datetime64[ns])':
   No match.

Edit: Gitter discussion here

This isn’t exactly what you asked, but with some sketchy assumptions (64-bit cython where id() is a pointer to the PyObject) and the great @stuartarchibald’s suggestion here you can dig the raw integer value directly from the PyObject.

I’d guess that this is made more complicated by the fact that we’re working with a scalar object; I think this would likelier be cleaner if you had a numpy array of these, then they’d all be lined up as integers in memory with a well-defined size and base address…

import numpy as np
from numba import njit, carray, int64
from numba.extending import intrinsic

@intrinsic
def address_as_void_pointer(typingctx, src):
    """ returns a void pointer from a given memory address """
    from numba.core import types, cgutils
    sig = types.voidptr(src)

    def codegen(cgctx, builder, sig, args):
        return builder.inttoptr(args[0], cgutils.voidptr_t)

    return sig, codegen

@njit
def f(dt_ptr):
    return carray(address_as_void_pointer(dt_ptr), 3, int64)[2]

dt = np.datetime64('2005-02-25')
print('python says', dt, dt.astype(np.int64), id(dt))
print('numba says', f(id(dt)))

Edit 2: Output is

python says 2005-02-25 12839 2851846899696
numba says 12839