Skip to content

Commit 4f628e8

Browse files
Fix: avoid object dtype inference warning in to_datetime
1 parent 3dc222d commit 4f628e8

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

pandas/core/tools/datetimes.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
import numpy as np
1818

19+
from pandas._config import using_string_dtype
20+
1921
from pandas._libs import (
2022
lib,
2123
tslib,
@@ -476,6 +478,9 @@ def _array_strptime_with_fallback(
476478
unit = np.datetime_data(result.dtype)[0]
477479
res = Index(result, dtype=f"M8[{unit}, UTC]", name=name)
478480
return res
481+
elif using_string_dtype() and result.dtype == object:
482+
if lib.is_string_array(result):
483+
return Index(result, dtype="str", name=name)
479484
return Index(result, dtype=result.dtype, name=name)
480485

481486

pandas/tests/tools/test_to_datetime.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1492,7 +1492,9 @@ def test_datetime_invalid_index(self, values, format):
14921492
warn, match="Could not infer format", raise_on_extra_warnings=False
14931493
):
14941494
res = to_datetime(values, errors="ignore", format=format)
1495-
tm.assert_index_equal(res, Index(values, dtype=object))
1495+
tm.assert_index_equal(
1496+
res, Index(values, dtype="object" if format is None else "str")
1497+
)
14961498

14971499
with tm.assert_produces_warning(
14981500
warn, match="Could not infer format", raise_on_extra_warnings=False
@@ -3713,7 +3715,7 @@ def test_to_datetime_mixed_not_necessarily_iso8601_raise():
37133715
("errors", "expected"),
37143716
[
37153717
("coerce", DatetimeIndex(["2020-01-01 00:00:00", NaT])),
3716-
("ignore", Index(["2020-01-01", "01-01-2000"], dtype=object)),
3718+
("ignore", Index(["2020-01-01", "01-01-2000"], dtype="str")),
37173719
],
37183720
)
37193721
def test_to_datetime_mixed_not_necessarily_iso8601_coerce(errors, expected):

0 commit comments

Comments
 (0)