Skip to content

Commit 31ead07

Browse files
author
Petr Baev
committed
DOC/ERR: better error message on unsuccessful datetime parsing #10720
1 parent 70a083f commit 31ead07

File tree

4 files changed

+33
-2
lines changed

4 files changed

+33
-2
lines changed

pandas/core/arrays/datetimes.py

+9
Original file line numberDiff line numberDiff line change
@@ -1970,6 +1970,15 @@ def objects_to_datetime64ns(
19701970
# return them as i8 to distinguish from wall times
19711971
return values.view("i8"), tz_parsed
19721972
except (ValueError, TypeError):
1973+
# GH#10720. If we failed to parse datetime then notify
1974+
# that flag errors='coerce' could be used to NaT.
1975+
# Trying to distinguish exception based on message.
1976+
if "Unknown string format" in e.args[0]:
1977+
msg = (
1978+
" ".join(e.args)
1979+
+ ". You can coerce to NaT by passing errors='coerce'"
1980+
)
1981+
e.args = (msg,)
19731982
raise e
19741983

19751984
if tz_parsed is not None:

pandas/core/tools/timedeltas.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -113,9 +113,11 @@ def _coerce_scalar_to_timedelta_type(r, unit="ns", errors="raise"):
113113

114114
try:
115115
result = Timedelta(r, unit)
116-
except ValueError:
116+
except ValueError as e:
117117
if errors == "raise":
118-
raise
118+
msg = e.args[0] + ". You can coerce to NaT by passing errors='coerce'"
119+
e.args = (msg,)
120+
raise e
119121
elif errors == "ignore":
120122
return r
121123

pandas/tests/indexes/datetimes/test_tools.py

+11
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,17 @@ def test_to_datetime_unparseable_ignore(self):
480480
s = "Month 1, 1999"
481481
assert pd.to_datetime(s, errors="ignore") == s
482482

483+
def test_to_datetime_unparseable_raise(self):
484+
# GH#10720
485+
s = "Month 1, 1999"
486+
expected_args = (
487+
f"Unknown string format: {s}. "
488+
f"You can coerce to NaT by passing errors='coerce'"
489+
)
490+
491+
with pytest.raises(ValueError, match=expected_args):
492+
pd.to_datetime(s, errors="raise")
493+
483494
@td.skip_if_windows # `tm.set_timezone` does not work in windows
484495
def test_to_datetime_now(self):
485496
# See GH#18666

pandas/tests/indexes/timedeltas/test_tools.py

+9
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,15 @@ def test_to_timedelta_invalid(self):
111111
invalid_data, to_timedelta(invalid_data, errors="ignore")
112112
)
113113

114+
# GH#10720
115+
invalid_data = "some_nonesense"
116+
expected_msg = (
117+
"unit abbreviation w/o a number. "
118+
"You can coerce to NaT by passing errors='coerce'"
119+
)
120+
with pytest.raises(ValueError, match=expected_msg):
121+
to_timedelta(invalid_data, errors="raise")
122+
114123
def test_to_timedelta_via_apply(self):
115124
# GH 5458
116125
expected = Series([np.timedelta64(1, "s")])

0 commit comments

Comments
 (0)