Skip to content

Commit 08885e4

Browse files
committed
handle error = ignore
1 parent 802e27c commit 08885e4

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

pandas/core/tools/datetimes.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -500,7 +500,8 @@ def _to_datetime_with_format(
500500
return _box_as_indexlike(result, utc=utc, name=name)
501501

502502
# GH#42957 #replacing all na with np.nan
503-
arg[isna(arg)] = np.nan
503+
if errors != "ignore":
504+
arg[isna(arg)] = np.nan
504505
# fallback
505506
res = _array_strptime_with_fallback(
506507
arg, name, tz, fmt, exact, errors, infer_datetime_format

pandas/tests/tools/test_to_datetime.py

+12
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,18 @@ def test_to_datetime_with_NA(self, data, format, expected):
199199
result = to_datetime(data, format=format)
200200
tm.assert_index_equal(result, expected)
201201

202+
def test_to_datetime_with_NA_and_errors(self):
203+
# GH#42957
204+
datelist = [pd.NA, 20210815, np.nan]
205+
result = to_datetime(datelist, format="%Y%m", errors="ignore")
206+
tm.assert_index_equal(result, Index(datelist))
207+
208+
result = to_datetime(datelist, format="%Y%m", errors="coerce")
209+
tm.assert_index_equal(result, DatetimeIndex(["NaT", "NaT", "NaT"]))
210+
211+
with pytest.raises(ValueError, match="unconverted data remains"):
212+
to_datetime(datelist, format="%Y%m", errors="raise")
213+
202214
@pytest.mark.parametrize("cache", [True, False])
203215
def test_to_datetime_format_integer(self, cache):
204216
# GH 10178

0 commit comments

Comments
 (0)