diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 2110f782330fb..c11eea603bc64 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -1852,14 +1852,20 @@ def objects_to_datetime64ns( yearfirst=yearfirst, require_iso8601=require_iso8601, ) - except ValueError as e: + except ValueError as err: try: values, tz_parsed = conversion.datetime_to_datetime64(data) # If tzaware, these values represent unix timestamps, so we # return them as i8 to distinguish from wall times return values.view("i8"), tz_parsed except (ValueError, TypeError): - raise e + if "Unknown string format" in err.args[0]: + raise ValueError( + f"Unexpected value {err.args[1]}.\n" + "You can coerce to NaT by passing `errors='coerce'`" + ) from err + + raise err if tz_parsed is not None: # We can take a shortcut since the datetime64 numpy array diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index d7529ec799022..48be7abc19dee 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -112,9 +112,12 @@ def _coerce_scalar_to_timedelta_type(r, unit="ns", errors="raise"): """Convert string 'r' to a timedelta object.""" try: result = Timedelta(r, unit) - except ValueError: + except ValueError as err: if errors == "raise": - raise + raise ValueError( + f"Unexpected value {err.args[0]}.\n" + "You can coerce to NaT by passing `errors='coerce'`" + ) from err elif errors == "ignore": return r diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index a91c837c9d9a2..d36e9782624fd 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -1630,7 +1630,10 @@ def test_string_na_nat_conversion(self, cache): malformed = np.array(["1/100/2000", np.nan], dtype=object) # GH 10636, default is now 'raise' - msg = r"Unknown string format:|day is out of range for month" + msg = ( + "Unexpected value 1/100/2000.\n" + "You can coerce to NaT by passing `errors='coerce'`" + ) with pytest.raises(ValueError, match=msg): to_datetime(malformed, errors="raise", cache=cache) diff --git a/pandas/tests/tools/test_to_timedelta.py b/pandas/tests/tools/test_to_timedelta.py index e3cf3a7f16a82..e8f42c4b9db53 100644 --- a/pandas/tests/tools/test_to_timedelta.py +++ b/pandas/tests/tools/test_to_timedelta.py @@ -121,6 +121,13 @@ def test_to_timedelta_invalid(self): invalid_data, to_timedelta(invalid_data, errors="ignore") ) + msg = ( + "Unexpected value unit abbreviation w/o a number.\n" + "You can coerce to NaT by passing `errors='coerce'`" + ) + with pytest.raises(ValueError, match=msg): + pd.to_timedelta("foo", errors="raise") + def test_to_timedelta_via_apply(self): # GH 5458 expected = Series([np.timedelta64(1, "s")])