Skip to content

Commit ca43cde

Browse files
BUG: ensure object dtype for strftime accessor/index method + REGR: avoid spurious warning (#48147)
1 parent 6d458ee commit ca43cde

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

doc/source/whatsnew/v1.4.4.rst

+1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ Bug fixes
3232
- 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`)
3333
- Bug in :meth:`DataFrame.to_sql` when ``method`` was a ``callable`` that did not return an ``int`` and would raise a ``TypeError`` (:issue:`46891`)
3434
- 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`)
35+
- 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`)
3536

3637
.. ---------------------------------------------------------------------------
3738

pandas/core/indexes/datetimes.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ def _new_DatetimeIndex(cls, d):
116116
+ [
117117
method
118118
for method in DatetimeArray._datetimelike_methods
119-
if method not in ("tz_localize", "tz_convert")
119+
if method not in ("tz_localize", "tz_convert", "strftime")
120120
],
121121
DatetimeArray,
122122
wrap=True,
@@ -270,7 +270,7 @@ def _engine_type(self) -> type[libindex.DatetimeEngine]:
270270
@doc(DatetimeArray.strftime)
271271
def strftime(self, date_format) -> Index:
272272
arr = self._data.strftime(date_format)
273-
return Index(arr, name=self.name)
273+
return Index(arr, name=self.name, dtype=object)
274274

275275
@doc(DatetimeArray.tz_convert)
276276
def tz_convert(self, tz) -> DatetimeIndex:

pandas/tests/series/accessors/test_dt_accessor.py

+11
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,17 @@ def test_strftime_nat(self, data):
618618
expected = Series(["2019-01-01", np.nan])
619619
tm.assert_series_equal(result, expected)
620620

621+
@pytest.mark.parametrize(
622+
"data", [DatetimeIndex([pd.NaT]), PeriodIndex([pd.NaT], dtype="period[D]")]
623+
)
624+
def test_strftime_all_nat(self, data):
625+
# https://github.com/pandas-dev/pandas/issues/45858
626+
ser = Series(data)
627+
with tm.assert_produces_warning(None):
628+
result = ser.dt.strftime("%Y-%m-%d")
629+
expected = Series([np.nan], dtype=object)
630+
tm.assert_series_equal(result, expected)
631+
621632
def test_valid_dt_with_missing_values(self):
622633

623634
from datetime import (

0 commit comments

Comments
 (0)