@@ -2,6 +2,7 @@ import cython
2
2
import numpy as np
3
3
4
4
cimport numpy as cnp
5
+ from cpython.object cimport PyObject
5
6
from numpy cimport (
6
7
int32_t,
7
8
int64_t,
@@ -273,7 +274,8 @@ def ensure_timedelta64ns(arr: ndarray, copy: bool = True):
273
274
274
275
@ cython.boundscheck (False )
275
276
@ cython.wraparound (False )
276
- def datetime_to_datetime64 (ndarray[object] values ):
277
+ def datetime_to_datetime64 (ndarray values ):
278
+ # ndarray[object], but can't declare object without ndim
277
279
"""
278
280
Convert ndarray of datetime-like objects to int64 array representing
279
281
nanosecond timestamps.
@@ -288,20 +290,27 @@ def datetime_to_datetime64(ndarray[object] values):
288
290
inferred_tz : tzinfo or None
289
291
"""
290
292
cdef:
291
- Py_ssize_t i, n = len ( values)
293
+ Py_ssize_t i, n = values.size
292
294
object val
293
- int64_t[:] iresult
295
+ int64_t ival
296
+ ndarray iresult # int64_t, but can't declare that without specifying ndim
294
297
npy_datetimestruct dts
295
298
_TSObject _ts
296
299
bint found_naive = False
297
300
tzinfo inferred_tz = None
298
301
299
- result = np.empty(n, dtype = ' M8[ns]' )
302
+ cnp.broadcast mi
303
+
304
+ result = np.empty((< object > values).shape, dtype = ' M8[ns]' )
300
305
iresult = result.view(' i8' )
306
+
307
+ mi = cnp.PyArray_MultiIterNew2(iresult, values)
301
308
for i in range (n):
302
- val = values[i]
309
+ # Analogous to: val = values[i]
310
+ val = < object > (< PyObject** > cnp.PyArray_MultiIter_DATA(mi, 1 ))[0 ]
311
+
303
312
if checknull_with_nat(val):
304
- iresult[i] = NPY_NAT
313
+ ival = NPY_NAT
305
314
elif PyDateTime_Check(val):
306
315
if val.tzinfo is not None :
307
316
if found_naive:
@@ -314,18 +323,23 @@ def datetime_to_datetime64(ndarray[object] values):
314
323
inferred_tz = val.tzinfo
315
324
316
325
_ts = convert_datetime_to_tsobject(val, None )
317
- iresult[i] = _ts.value
326
+ ival = _ts.value
318
327
check_dts_bounds(& _ts.dts)
319
328
else :
320
329
found_naive = True
321
330
if inferred_tz is not None :
322
331
raise ValueError (' Cannot mix tz-aware with '
323
332
' tz-naive values' )
324
- iresult[i] = pydatetime_to_dt64(val, & dts)
333
+ ival = pydatetime_to_dt64(val, & dts)
325
334
check_dts_bounds(& dts)
326
335
else :
327
336
raise TypeError (f' Unrecognized value type: {type(val)}' )
328
337
338
+ # Analogous to: iresult[i] = ival
339
+ (< int64_t* > cnp.PyArray_MultiIter_DATA(mi, 0 ))[0 ] = ival
340
+
341
+ cnp.PyArray_MultiIter_NEXT(mi)
342
+
329
343
return result, inferred_tz
330
344
331
345
0 commit comments