Skip to content

Commit 6ac4d74

Browse files
committed
BUG: to_timedelta not properly converting some units (GH6855)
1 parent 6387f38 commit 6ac4d74

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

pandas/tseries/tests/test_timedeltas.py

+11
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,17 @@ def conv(v):
199199
expected = Series([ np.timedelta64(1,'D') ]*5)
200200
tm.assert_series_equal(result, expected)
201201

202+
# validate all units
203+
# GH 6855
204+
for unit in ['Y','M','W','D','y','w','d']:
205+
result = to_timedelta(np.arange(5),unit=unit)
206+
expected = Series([ np.timedelta64(i,unit.upper()) for i in np.arange(5).tolist() ])
207+
tm.assert_series_equal(result, expected)
208+
for unit in ['h','m','s','ms','us','ns','H','S','MS','US','NS']:
209+
result = to_timedelta(np.arange(5),unit=unit)
210+
expected = Series([ np.timedelta64(i,unit.lower()) for i in np.arange(5).tolist() ])
211+
tm.assert_series_equal(result, expected)
212+
202213
# these will error
203214
self.assertRaises(ValueError, lambda : to_timedelta(['1h']))
204215
self.assertRaises(ValueError, lambda : to_timedelta(['1m']))

pandas/tseries/timedeltas.py

+11
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ def _convert_listlike(arg, box, unit):
4040
if is_timedelta64_dtype(arg):
4141
value = arg.astype('timedelta64[ns]')
4242
elif is_integer_dtype(arg):
43+
unit = _validate_timedelta_unit(unit)
44+
4345
# these are shortcutable
4446
value = arg.astype('timedelta64[{0}]'.format(unit)).astype('timedelta64[ns]')
4547
else:
@@ -65,6 +67,15 @@ def _convert_listlike(arg, box, unit):
6567
# ...so it must be a scalar value. Return scalar.
6668
return _coerce_scalar_to_timedelta_type(arg, unit=unit)
6769

70+
def _validate_timedelta_unit(arg):
71+
""" provide validation / translation for timedelta short units """
72+
73+
if re.search("Y|W|D",arg,re.IGNORECASE) or arg == 'M':
74+
return arg.upper()
75+
elif re.search("h|m|s|ms|us|ns",arg,re.IGNORECASE):
76+
return arg.lower()
77+
raise ValueError("invalid timedelta unit {0} provided".format(arg))
78+
6879
_short_search = re.compile(
6980
"^\s*(?P<neg>-?)\s*(?P<value>\d*\.?\d*)\s*(?P<unit>d|s|ms|us|ns)?\s*$",re.IGNORECASE)
7081
_full_search = re.compile(

0 commit comments

Comments
 (0)