1
1
import numpy as np
2
2
3
3
cimport numpy as cnp
4
+ from libc.math cimport log10
4
5
from numpy cimport (
5
6
int32_t,
6
7
int64_t,
@@ -84,7 +85,7 @@ TD64NS_DTYPE = np.dtype("m8[ns]")
84
85
cdef int64_t cast_from_unit(
85
86
object ts,
86
87
str unit,
87
- NPY_DATETIMEUNIT reso = NPY_FR_ns
88
+ NPY_DATETIMEUNIT out_reso = NPY_FR_ns
88
89
) except ? - 1 :
89
90
"""
90
91
Return a casting of the unit represented to nanoseconds
@@ -103,7 +104,7 @@ cdef int64_t cast_from_unit(
103
104
int64_t m
104
105
int p
105
106
106
- m, p = precision_from_unit(unit, reso )
107
+ m, p = precision_from_unit(unit, out_reso )
107
108
108
109
# just give me the unit back
109
110
if ts is None :
@@ -123,7 +124,7 @@ cdef int64_t cast_from_unit(
123
124
if is_float_object(ts):
124
125
ts = int (ts)
125
126
dt64obj = np.datetime64(ts, unit)
126
- return get_datetime64_nanos(dt64obj, reso )
127
+ return get_datetime64_nanos(dt64obj, out_reso )
127
128
128
129
# cast the unit, multiply base/frac separately
129
130
# to avoid precision issues from float -> int
@@ -165,16 +166,7 @@ cpdef inline (int64_t, int) precision_from_unit(
165
166
int p
166
167
NPY_DATETIMEUNIT reso = abbrev_to_npy_unit(unit)
167
168
168
- if out_reso == NPY_DATETIMEUNIT.NPY_FR_ns:
169
- multiplier = 1 _000_000_000
170
- elif out_reso == NPY_DATETIMEUNIT.NPY_FR_us:
171
- multiplier = 1 _000_000
172
- elif out_reso == NPY_DATETIMEUNIT.NPY_FR_ms:
173
- multiplier = 1 _000
174
- elif out_reso == NPY_DATETIMEUNIT.NPY_FR_s:
175
- multiplier = 1
176
- else :
177
- raise ValueError (f" Invalid out_reso: {out_reso}" )
169
+ multiplier = periods_per_second(out_reso)
178
170
179
171
if reso == NPY_DATETIMEUNIT.NPY_FR_Y:
180
172
# each 400 years we have 97 leap years, for an average of 97/400=.2425
@@ -202,7 +194,7 @@ cpdef inline (int64_t, int) precision_from_unit(
202
194
m = multiplier // 1 _000_000_000
203
195
else :
204
196
raise ValueError (f" cannot cast unit {unit}" )
205
- p = min ( 9 , len ( str (m)) - 1 )
197
+ p = < int > log10(m) # number of digits in 'm' minus 1
206
198
return m, p
207
199
208
200
0 commit comments