Skip to content

Commit f9d4161

Browse files
committed
fix bad datetime to str conversion in Series ctor _try_cast and add a test (#57512)
1 parent 89898a6 commit f9d4161

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

pandas/_libs/lib.pyx

+2-1
Original file line numberDiff line numberDiff line change
@@ -757,7 +757,8 @@ cpdef ndarray[object] ensure_string_array(
757757
# dtype check to exclude DataFrame
758758
# GH#41409 TODO: not a great place for this
759759
out = arr.astype(str).astype(object)
760-
out[arr.isna()] = na_value
760+
if convert_na_value:
761+
out[arr.isna()] = na_value
761762
return out
762763
arr = arr.to_numpy(dtype=object)
763764
elif not util.is_array(arr):

pandas/core/construction.py

+1
Original file line numberDiff line numberDiff line change
@@ -800,6 +800,7 @@ def _try_cast(
800800
shape = arr.shape
801801
if arr.ndim > 1:
802802
arr = arr.ravel()
803+
arr = ensure_wrapped_if_datetimelike(arr)
803804
else:
804805
shape = (len(arr),)
805806
return lib.ensure_string_array(arr, convert_na_value=False, copy=copy).reshape(

pandas/tests/series/test_constructors.py

+17
Original file line numberDiff line numberDiff line change
@@ -615,6 +615,23 @@ def test_constructor_maskedarray(self):
615615
)
616616
tm.assert_series_equal(result, expected)
617617

618+
@pytest.mark.parametrize("dtype", ["M8[s]", "M8[ms]", "M8[us]", "M8[ns]"])
619+
def test_constructor_str_object_datetime_array(self, dtype):
620+
# GH 57512
621+
dt_arr = np.array(
622+
[
623+
"2024-01-03T00:00:00.000000000",
624+
"2024-01-01T00:00:00.000000000",
625+
],
626+
dtype=dtype,
627+
)
628+
result = Series(Series(dt_arr, dtype=str), dtype=dtype)
629+
expected = Series(dt_arr, dtype=dtype)
630+
tm.assert_series_equal(result, expected)
631+
632+
result = Series(Series(dt_arr, dtype=object), dtype=dtype)
633+
tm.assert_series_equal(result, expected)
634+
618635
def test_constructor_maskedarray_hardened(self):
619636
# Check numpy masked arrays with hard masks -- from GH24574
620637
data = ma.masked_all((3,), dtype=float).harden_mask()

0 commit comments

Comments
 (0)