Skip to content

BUG: Fix DatetimeIndex.strftime with NaT present #29583

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ Datetimelike
- Bug in :func:`pandas.core.groupby.generic.SeriesGroupBy.apply` raising ``ValueError`` when a column in the original DataFrame is a datetime and the column labels are not standard integers (:issue:`28247`)
- Bug in :func:`pandas._config.localization.get_locales` where the ``locales -a`` encodes the locales list as windows-1252 (:issue:`23638`, :issue:`24760`, :issue:`27368`)
- Bug in :meth:`Series.var` failing to raise ``TypeError`` when called with ``timedelta64[ns]`` dtype (:issue:`28289`)
-
- Bug in :meth:`DatetimeIndex.strftime` and :meth:`Series.dt.strftime` where ``NaT`` was converted to the string ``'NaT'`` instead of ``np.nan`` (:issue:`29578`)

Timedelta
^^^^^^^^^
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,8 @@ def strftime(self, date_format):
'March 10, 2018, 09:00:02 AM'],
dtype='object')
"""
return self._format_native_types(date_format=date_format).astype(object)
result = self._format_native_types(date_format=date_format, na_rep=np.nan)
return result.astype(object)


class TimelikeOps:
Expand Down
20 changes: 18 additions & 2 deletions pandas/tests/arrays/test_datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,15 @@ def test_strftime(self, datetime_index):
arr = DatetimeArray(datetime_index)

result = arr.strftime("%Y %b")
expected = np.array(datetime_index.strftime("%Y %b"))
expected = np.array([ts.strftime("%Y %b") for ts in arr], dtype=object)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change isn't directly related to the PR but something I noticed along the way. I don't think the previous version is completely valid: DatetimeIndex delegates to DatetimeArray for strftime so it was basically testing against itself.

tm.assert_numpy_array_equal(result, expected)

def test_strftime_nat(self):
# GH 29578
arr = DatetimeArray(DatetimeIndex(["2019-01-01", pd.NaT]))

result = arr.strftime("%Y-%m-%d")
expected = np.array(["2019-01-01", np.nan], dtype=object)
tm.assert_numpy_array_equal(result, expected)


Expand Down Expand Up @@ -679,7 +687,15 @@ def test_strftime(self, period_index):
arr = PeriodArray(period_index)

result = arr.strftime("%Y")
expected = np.array(period_index.strftime("%Y"))
expected = np.array([per.strftime("%Y") for per in arr], dtype=object)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same thing as my other comment about this pattern for DatetimeArray.

tm.assert_numpy_array_equal(result, expected)

def test_strftime_nat(self):
# GH 29578
arr = PeriodArray(PeriodIndex(["2019-01-01", pd.NaT], dtype="period[D]"))
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is working fine for PeriodArray and PeriodIndex on master; added this test since I didn't see an existing one for this behavior.


result = arr.strftime("%Y-%m-%d")
expected = np.array(["2019-01-01", np.nan], dtype=object)
tm.assert_numpy_array_equal(result, expected)


Expand Down
16 changes: 15 additions & 1 deletion pandas/tests/series/test_datetime_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ def test_strftime(self):
s.iloc[0] = pd.NaT
result = s.dt.strftime("%Y/%m/%d")
expected = Series(
["NaT", "2013/01/02", "2013/01/03", "2013/01/04", "2013/01/05"]
[np.nan, "2013/01/02", "2013/01/03", "2013/01/04", "2013/01/05"]
)
tm.assert_series_equal(result, expected)

Expand Down Expand Up @@ -554,6 +554,20 @@ def test_strftime(self):
)
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize(
"data",
[
DatetimeIndex(["2019-01-01", pd.NaT]),
PeriodIndex(["2019-01-01", pd.NaT], dtype="period[D]"),
],
)
def test_strftime_nat(self, data):
# GH 29578
s = Series(data)
result = s.dt.strftime("%Y-%m-%d")
expected = Series(["2019-01-01", np.nan])
tm.assert_series_equal(result, expected)

def test_valid_dt_with_missing_values(self):

from datetime import date, time
Expand Down