12
12
is_timedelta64_dtype , _values_from_object ,
13
13
is_list_like , isnull , _ensure_object )
14
14
15
- def to_timedelta (arg , unit = 'ns' , box = True ):
15
+ def to_timedelta (arg , unit = 'ns' , box = True , coerce = False ):
16
16
"""
17
17
Convert argument to timedelta
18
18
@@ -23,6 +23,7 @@ def to_timedelta(arg, unit='ns', box=True):
23
23
box : boolean, default True
24
24
If True returns a Timedelta/TimedeltaIndex of the results
25
25
if False returns a np.timedelta64 or ndarray of values of dtype timedelta64[ns]
26
+ coerce : force errors to NaT (False by default)
26
27
27
28
Returns
28
29
-------
@@ -43,14 +44,14 @@ def _convert_listlike(arg, box, unit):
43
44
value = arg .astype ('timedelta64[{0}]' .format (unit )).astype ('timedelta64[ns]' )
44
45
else :
45
46
try :
46
- value = tslib .array_to_timedelta64 (_ensure_object (arg ), unit = unit )
47
+ value = tslib .array_to_timedelta64 (_ensure_object (arg ), unit = unit , coerce = coerce )
47
48
except :
48
49
49
50
# try to process strings fast; may need to fallback
50
51
try :
51
52
value = np .array ([ _get_string_converter (r , unit = unit )() for r in arg ],dtype = 'm8[ns]' )
52
53
except :
53
- value = np .array ([ _coerce_scalar_to_timedelta_type (r , unit = unit ) for r in arg ])
54
+ value = np .array ([ _coerce_scalar_to_timedelta_type (r , unit = unit , coerce = coerce ) for r in arg ])
54
55
55
56
if box :
56
57
from pandas import TimedeltaIndex
@@ -67,7 +68,7 @@ def _convert_listlike(arg, box, unit):
67
68
return _convert_listlike (arg , box = box , unit = unit )
68
69
69
70
# ...so it must be a scalar value. Return scalar.
70
- return _coerce_scalar_to_timedelta_type (arg , unit = unit , box = box )
71
+ return _coerce_scalar_to_timedelta_type (arg , unit = unit , box = box , coerce = coerce )
71
72
72
73
_unit_map = {
73
74
'Y' : 'Y' ,
@@ -135,7 +136,7 @@ def _validate_timedelta_unit(arg):
135
136
_full_search2 = re .compile ('' .join (
136
137
["^\s*(?P<neg>-?)\s*" ] + [ "(?P<" + p + ">\\ d+\.?\d*\s*(" + ss + "))?\\ s*" for p , ss in abbrevs ] + ['$' ]))
137
138
138
- def _coerce_scalar_to_timedelta_type (r , unit = 'ns' , box = True ):
139
+ def _coerce_scalar_to_timedelta_type (r , unit = 'ns' , box = True , coerce = False ):
139
140
""" convert strings to timedelta; coerce to Timedelta (if box), else np.timedelta64"""
140
141
141
142
if isinstance (r , compat .string_types ):
@@ -145,7 +146,7 @@ def _coerce_scalar_to_timedelta_type(r, unit='ns', box=True):
145
146
r = converter ()
146
147
unit = 'ns'
147
148
148
- result = tslib .convert_to_timedelta (r ,unit )
149
+ result = tslib .convert_to_timedelta (r ,unit , coerce )
149
150
if box :
150
151
result = tslib .Timedelta (result )
151
152
@@ -262,32 +263,3 @@ def convert(r=None, unit=None, m=m):
262
263
# no converter
263
264
raise ValueError ("cannot create timedelta string converter for [{0}]" .format (r ))
264
265
265
- def _possibly_cast_to_timedelta (value , coerce = True , dtype = None ):
266
- """ try to cast to timedelta64, if already a timedeltalike, then make
267
- sure that we are [ns] (as numpy 1.6.2 is very buggy in this regards,
268
- don't force the conversion unless coerce is True
269
-
270
- if dtype is passed then this is the target dtype
271
- """
272
-
273
- # deal with numpy not being able to handle certain timedelta operations
274
- if isinstance (value , (ABCSeries , np .ndarray )):
275
-
276
- # i8 conversions
277
- if value .dtype == 'int64' and np .dtype (dtype ) == 'timedelta64[ns]' :
278
- value = value .astype ('timedelta64[ns]' )
279
- return value
280
- elif value .dtype .kind == 'm' :
281
- if value .dtype != 'timedelta64[ns]' :
282
- value = value .astype ('timedelta64[ns]' )
283
- return value
284
-
285
- # we don't have a timedelta, but we want to try to convert to one (but
286
- # don't force it)
287
- if coerce :
288
- new_value = tslib .array_to_timedelta64 (
289
- _values_from_object (value ).astype (object ), coerce = False )
290
- if new_value .dtype == 'i8' :
291
- value = np .array (new_value , dtype = 'timedelta64[ns]' )
292
-
293
- return value
0 commit comments