@@ -13,7 +13,7 @@ from cpython cimport PyUnicode_Check, Py_NE, Py_EQ, PyObject_RichCompare
13
13
14
14
import numpy as np
15
15
cimport numpy as cnp
16
- from numpy cimport int64_t, ndarray
16
+ from numpy cimport int64_t
17
17
cnp.import_array()
18
18
19
19
from cpython.datetime cimport (datetime, timedelta,
@@ -33,6 +33,7 @@ from np_datetime cimport (cmp_scalar, reverse_ops, td64_to_tdstruct,
33
33
34
34
from nattype import nat_strings, NaT
35
35
from nattype cimport checknull_with_nat, NPY_NAT
36
+ from offsets cimport to_offset
36
37
37
38
# ----------------------------------------------------------------------
38
39
# Constants
@@ -78,6 +79,44 @@ cdef dict timedelta_abbrevs = { 'D': 'd',
78
79
79
80
_no_input = object ()
80
81
82
+
83
+ # ----------------------------------------------------------------------
84
+ # API
85
+
86
+ def ints_to_pytimedelta (int64_t[:] arr , box = False ):
87
+ """
88
+ convert an i8 repr to an ndarray of timedelta or Timedelta (if box ==
89
+ True)
90
+
91
+ Parameters
92
+ ----------
93
+ arr : ndarray[int64_t]
94
+ box : bool, default False
95
+
96
+ Returns
97
+ -------
98
+ result : ndarray[object]
99
+ array of Timedelta or timedeltas objects
100
+ """
101
+ cdef:
102
+ Py_ssize_t i, n = len (arr)
103
+ int64_t value
104
+ object [:] result = np.empty(n, dtype = object )
105
+
106
+ for i in range (n):
107
+
108
+ value = arr[i]
109
+ if value == NPY_NAT:
110
+ result[i] = NaT
111
+ else :
112
+ if box:
113
+ result[i] = Timedelta(value)
114
+ else :
115
+ result[i] = timedelta(microseconds = int (value) / 1000 )
116
+
117
+ return result.base # .base to access underlying np.ndarray
118
+
119
+
81
120
# ----------------------------------------------------------------------
82
121
83
122
cpdef int64_t delta_to_nanoseconds(delta) except ? - 1 :
@@ -144,7 +183,11 @@ cpdef convert_to_timedelta64(object ts, object unit):
144
183
ts = cast_from_unit(ts, unit)
145
184
ts = np.timedelta64(ts)
146
185
elif is_string_object(ts):
147
- ts = np.timedelta64(parse_timedelta_string(ts))
186
+ if len (ts) > 0 and ts[0 ] == ' P' :
187
+ ts = parse_iso_format_string(ts)
188
+ else :
189
+ ts = parse_timedelta_string(ts)
190
+ ts = np.timedelta64(ts)
148
191
elif hasattr (ts, ' delta' ):
149
192
ts = np.timedelta64(delta_to_nanoseconds(ts), ' ns' )
150
193
@@ -156,15 +199,15 @@ cpdef convert_to_timedelta64(object ts, object unit):
156
199
return ts.astype(' timedelta64[ns]' )
157
200
158
201
159
- cpdef array_to_timedelta64(ndarray[ object ] values, unit = ' ns' , errors = ' raise' ):
202
+ cpdef array_to_timedelta64(object [: ] values, unit = ' ns' , errors = ' raise' ):
160
203
"""
161
204
Convert an ndarray to an array of timedeltas. If errors == 'coerce',
162
205
coerce non-convertible objects to NaT. Otherwise, raise.
163
206
"""
164
207
165
208
cdef:
166
209
Py_ssize_t i, n
167
- ndarray[ int64_t] iresult
210
+ int64_t[: ] iresult
168
211
169
212
if errors not in (' ignore' , ' raise' , ' coerce' ):
170
213
raise ValueError (" errors must be one of 'ignore', "
@@ -190,7 +233,7 @@ cpdef array_to_timedelta64(ndarray[object] values, unit='ns', errors='raise'):
190
233
else :
191
234
raise
192
235
193
- return iresult
236
+ return iresult.base # .base to access underlying np.ndarray
194
237
195
238
196
239
cpdef inline int64_t cast_from_unit(object ts, object unit) except ? - 1 :
@@ -795,12 +838,81 @@ cdef class _Timedelta(timedelta):
795
838
796
839
@property
797
840
def asm8 (self ):
798
- """ return a numpy timedelta64 array view of myself """
841
+ """
842
+ Return a numpy timedelta64 array scalar view.
843
+
844
+ Provides access to the array scalar view (i.e. a combination of the
845
+ value and the units) associated with the numpy.timedelta64().view(),
846
+ including a 64-bit integer representation of the timedelta in
847
+ nanoseconds (Python int compatible).
848
+
849
+ Returns
850
+ -------
851
+ numpy timedelta64 array scalar view
852
+ Array scalar view of the timedelta in nanoseconds.
853
+
854
+ Examples
855
+ --------
856
+ >>> td = pd.Timedelta('1 days 2 min 3 us 42 ns')
857
+ >>> td.asm8
858
+ numpy.timedelta64(86520000003042,'ns')
859
+
860
+ >>> td = pd.Timedelta('2 min 3 s')
861
+ >>> td.asm8
862
+ numpy.timedelta64(123000000000,'ns')
863
+
864
+ >>> td = pd.Timedelta('3 ms 5 us')
865
+ >>> td.asm8
866
+ numpy.timedelta64(3005000,'ns')
867
+
868
+ >>> td = pd.Timedelta(42, unit='ns')
869
+ >>> td.asm8
870
+ numpy.timedelta64(42,'ns')
871
+ """
799
872
return np.int64(self .value).view(' m8[ns]' )
800
873
801
874
@property
802
875
def resolution (self ):
803
- """ return a string representing the lowest resolution that we have """
876
+ """
877
+ Return a string representing the lowest timedelta resolution.
878
+
879
+ Each timedelta has a defined resolution that represents the lowest OR
880
+ most granular level of precision. Each level of resolution is
881
+ represented by a short string as defined below:
882
+
883
+ Resolution: Return value
884
+
885
+ * Days: 'D'
886
+ * Hours: 'H'
887
+ * Minutes: 'T'
888
+ * Seconds: 'S'
889
+ * Milliseconds: 'L'
890
+ * Microseconds: 'U'
891
+ * Nanoseconds: 'N'
892
+
893
+ Returns
894
+ -------
895
+ str
896
+ Timedelta resolution.
897
+
898
+ Examples
899
+ --------
900
+ >>> td = pd.Timedelta('1 days 2 min 3 us 42 ns')
901
+ >>> td.resolution
902
+ 'N'
903
+
904
+ >>> td = pd.Timedelta('1 days 2 min 3 us')
905
+ >>> td.resolution
906
+ 'U'
907
+
908
+ >>> td = pd.Timedelta('2 min 3 s')
909
+ >>> td.resolution
910
+ 'S'
911
+
912
+ >>> td = pd.Timedelta(36, unit='us')
913
+ >>> td.resolution
914
+ 'U'
915
+ """
804
916
805
917
self ._ensure_components()
806
918
if self ._ns:
@@ -904,6 +1016,9 @@ cdef class _Timedelta(timedelta):
904
1016
def __str__ (self ):
905
1017
return self ._repr_base(format = ' long' )
906
1018
1019
+ def __bool__ (self ):
1020
+ return self .value != 0
1021
+
907
1022
def isoformat (self ):
908
1023
"""
909
1024
Format Timedelta as ISO 8601 Duration like
@@ -1063,7 +1178,6 @@ class Timedelta(_Timedelta):
1063
1178
cdef:
1064
1179
int64_t result, unit
1065
1180
1066
- from pandas.tseries.frequencies import to_offset
1067
1181
unit = to_offset(freq).nanos
1068
1182
result = unit * rounder(self .value / float (unit))
1069
1183
return Timedelta(result, unit = ' ns' )
0 commit comments