diff --git a/doc/source/whatsnew/v1.4.4.rst b/doc/source/whatsnew/v1.4.4.rst index 96e4ad4321c60..5fcd27dd39884 100644 --- a/doc/source/whatsnew/v1.4.4.rst +++ b/doc/source/whatsnew/v1.4.4.rst @@ -32,6 +32,7 @@ Bug fixes - The :class:`errors.FutureWarning` raised when passing arguments (other than ``filepath_or_buffer``) as positional in :func:`read_csv` is now raised at the correct stacklevel (:issue:`47385`) - Bug in :meth:`DataFrame.to_sql` when ``method`` was a ``callable`` that did not return an ``int`` and would raise a ``TypeError`` (:issue:`46891`) - Bug in :meth:`loc.__getitem__` with a list of keys causing an internal inconsistency that could lead to a disconnect between ``frame.at[x, y]`` vs ``frame[y].loc[x]`` (:issue:`22372`) +- Bug in the :meth:`Series.dt.strftime` accessor return a float instead of object dtype Series for all-NaT input, which also causes a spurious deprecation warning (:issue:`45858`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 004d860b20a6f..4f93db4499a30 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -110,7 +110,7 @@ def _new_DatetimeIndex(cls, d): + [ method for method in DatetimeArray._datetimelike_methods - if method not in ("tz_localize", "tz_convert") + if method not in ("tz_localize", "tz_convert", "strftime") ], DatetimeArray, wrap=True, @@ -261,7 +261,7 @@ class DatetimeIndex(DatetimeTimedeltaMixin): @doc(DatetimeArray.strftime) def strftime(self, date_format) -> Index: arr = self._data.strftime(date_format) - return Index(arr, name=self.name) + return Index(arr, name=self.name, dtype=object) @doc(DatetimeArray.tz_convert) def tz_convert(self, tz) -> DatetimeIndex: diff --git a/pandas/tests/series/accessors/test_dt_accessor.py b/pandas/tests/series/accessors/test_dt_accessor.py index 41b5e55e75213..fe4b25026ac74 100644 --- a/pandas/tests/series/accessors/test_dt_accessor.py +++ b/pandas/tests/series/accessors/test_dt_accessor.py @@ -618,6 +618,17 @@ def test_strftime_nat(self, data): expected = Series(["2019-01-01", np.nan]) tm.assert_series_equal(result, expected) + @pytest.mark.parametrize( + "data", [DatetimeIndex([pd.NaT]), PeriodIndex([pd.NaT], dtype="period[D]")] + ) + def test_strftime_all_nat(self, data): + # https://github.com/pandas-dev/pandas/issues/45858 + ser = Series(data) + with tm.assert_produces_warning(None): + result = ser.dt.strftime("%Y-%m-%d") + expected = Series([np.nan], dtype=object) + tm.assert_series_equal(result, expected) + def test_valid_dt_with_missing_values(self): from datetime import (