Skip to content

BUG: Invalid Timedelta op may raise ValueError #13624

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.19.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,7 @@ Bug Fixes
- Bug in ``.to_html``, ``.to_latex`` and ``.to_string`` silently ignore custom datetime formatter passed through the ``formatters`` key word (:issue:`10690`)

- Bug in ``pd.to_numeric`` when ``errors='coerce'`` and input contains non-hashable objects (:issue:`13324`)

- Bug in invalid ``Timedelta`` arithmetic and comparison may raise ``ValueError`` rather than ``TypeError`` (:issue:`13624`)

- Bug in ``Categorical.remove_unused_categories()`` changes ``.codes`` dtype to platform int (:issue:`13261`)
- Bug in ``groupby`` with ``as_index=False`` returns all NaN's when grouping on multiple columns including a categorical one (:issue:`13204`)
Expand Down
10 changes: 7 additions & 3 deletions pandas/tseries/tdi.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,20 @@ def _td_index_cmp(opname, nat_result=False):
"""

def wrapper(self, other):
msg = "cannot compare a TimedeltaIndex with type {0}"
func = getattr(super(TimedeltaIndex, self), opname)
if _is_convertible_to_td(other) or other is tslib.NaT:
other = _to_m8(other)
try:
other = _to_m8(other)
except ValueError:
# failed to parse as timedelta
raise TypeError(msg.format(type(other)))
result = func(other)
if com.isnull(other):
result.fill(nat_result)
else:
if not com.is_list_like(other):
raise TypeError("cannot compare a TimedeltaIndex with type "
"{0}".format(type(other)))
raise TypeError(msg.format(type(other)))

other = TimedeltaIndex(other).values
result = func(other)
Expand Down
32 changes: 32 additions & 0 deletions pandas/tseries/tests/test_timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,21 @@ class Other:
self.assertTrue(td.__mul__(other) is NotImplemented)
self.assertTrue(td.__floordiv__(td) is NotImplemented)

def test_ops_error_str(self):
# GH 13624
td = Timedelta('1 day')

for l, r in [(td, 'a'), ('a', td)]:

with tm.assertRaises(TypeError):
l + r

with tm.assertRaises(TypeError):
l > r

self.assertFalse(l == r)
self.assertTrue(l != r)

def test_fields(self):
def check(value):
# that we are int/long like
Expand Down Expand Up @@ -1432,6 +1447,23 @@ def test_comparisons_nat(self):
expected = np.array([True, True, True, True, True, False])
self.assert_numpy_array_equal(result, expected)

def test_ops_error_str(self):
# GH 13624
tdi = TimedeltaIndex(['1 day', '2 days'])

for l, r in [(tdi, 'a'), ('a', tdi)]:
with tm.assertRaises(TypeError):
l + r

with tm.assertRaises(TypeError):
l > r

with tm.assertRaises(TypeError):
l == r

with tm.assertRaises(TypeError):
l != r

def test_map(self):

rng = timedelta_range('1 day', periods=10)
Expand Down
4 changes: 2 additions & 2 deletions pandas/tseries/timedeltas.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ def _convert_listlike(arg, box, unit, name=None):
value = arg.astype('timedelta64[{0}]'.format(
unit)).astype('timedelta64[ns]', copy=False)
else:
value = tslib.array_to_timedelta64(
_ensure_object(arg), unit=unit, errors=errors)
value = tslib.array_to_timedelta64(_ensure_object(arg),
unit=unit, errors=errors)
value = value.astype('timedelta64[ns]', copy=False)

if box:
Expand Down
9 changes: 8 additions & 1 deletion pandas/tslib.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -2912,10 +2912,17 @@ class Timedelta(_Timedelta):
if not self._validate_ops_compat(other):
return NotImplemented

other = Timedelta(other)
if other is NaT:
return NaT

try:
other = Timedelta(other)
except ValueError:
# failed to parse as timedelta
return NotImplemented

return Timedelta(op(self.value, other.value), unit='ns')

f.__name__ = name
return f

Expand Down