Skip to content

Commit a8af83d

Browse files
committed
FIX: date comparison fails when series is all pd.NaT values #61188
1 parent 29d2c56 commit a8af83d

File tree

3 files changed

+9
-52
lines changed

3 files changed

+9
-52
lines changed

doc/source/whatsnew/v3.0.0.rst

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,7 @@ Categorical
642642
Datetimelike
643643
^^^^^^^^^^^^
644644
- Bug in :attr:`is_year_start` where a DateTimeIndex constructed via a date_range with frequency 'MS' wouldn't have the correct year or quarter start attributes (:issue:`57377`)
645+
- Bug in :attr:`Series.dt.date` where Series with all NaT values would raise an error when compared to a datetime.date (:issue:`61188`)
645646
- Bug in :class:`DataFrame` raising ``ValueError`` when ``dtype`` is ``timedelta64`` and ``data`` is a list containing ``None`` (:issue:`60064`)
646647
- Bug in :class:`Timestamp` constructor failing to raise when ``tz=None`` is explicitly specified in conjunction with timezone-aware ``tzinfo`` or data (:issue:`48688`)
647648
- Bug in :func:`date_range` where the last valid timestamp would sometimes not be produced (:issue:`56134`)
@@ -656,11 +657,9 @@ Datetimelike
656657
- Bug in :meth:`Series.dt.microsecond` producing incorrect results for pyarrow backed :class:`Series`. (:issue:`59154`)
657658
- Bug in :meth:`to_datetime` not respecting dayfirst if an uncommon date string was passed. (:issue:`58859`)
658659
- Bug in :meth:`to_datetime` on float array with missing values throwing ``FloatingPointError`` (:issue:`58419`)
659-
- Bug in :meth:`to_datetime` on float32 df with year, month, day etc. columns leads to precision issues and incorrect result. (:issue:`60506`)
660660
- Bug in :meth:`to_datetime` reports incorrect index in case of any failure scenario. (:issue:`58298`)
661661
- Bug in :meth:`to_datetime` wrongly converts when ``arg`` is a ``np.datetime64`` object with unit of ``ps``. (:issue:`60341`)
662662
- Bug in setting scalar values with mismatched resolution into arrays with non-nanosecond ``datetime64``, ``timedelta64`` or :class:`DatetimeTZDtype` incorrectly truncating those scalars (:issue:`56410`)
663-
- Bug in :attr:`Series.dt.date` where Series with all NaT values would raise an error when compared to a datetime.date (:issue:`61188`)
664663

665664
Timedelta
666665
^^^^^^^^^

pandas/core/indexes/accessors.py

Lines changed: 4 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,11 @@
1111
)
1212
import warnings
1313

14+
1415
import numpy as np
1516

17+
18+
1619
from pandas._libs import lib
1720
from pandas.util._exceptions import find_stack_level
1821

@@ -108,7 +111,7 @@ def _delegate_property_get(self, name: str):
108111
else:
109112
index = self._parent.index
110113
# return the result as a Series
111-
return Series(result, index=index, name=self.name).__finalize__(self._parent)
114+
return Series(result, index=index, name=self.name, dtype=result.dtype).__finalize__(self._parent)
112115

113116
def _delegate_property_set(self, name: str, value, *args, **kwargs) -> NoReturn:
114117
raise ValueError(
@@ -396,53 +399,6 @@ def freq(self):
396399
'2YS-JAN'
397400
"""
398401
return self._get_values().inferred_freq
399-
400-
@property
401-
def date(self):
402-
"""
403-
Return the date component (year, month, day) of each datetime in the Series.
404-
405-
This property returns a Series of Python datetime.date objects corresponding to
406-
the date portion of each datetime64[ns] value in the Series. For missing values
407-
(NaT), the result will be NaT.
408-
409-
Returns
410-
-------
411-
Series
412-
A Series of datetime.date objects or NaT, with dtype object.
413-
414-
Notes
415-
-----
416-
- The result is always returned with object dtype.
417-
- This ensures comparisons with Python datetime.date values (e.g. using <=)
418-
work even when the Series contains only missing values (NaT).
419-
420-
Examples
421-
--------
422-
>>> s = pd.Series(pd.to_datetime(["2020-01-01", pd.NaT]))
423-
>>> s.dt.date
424-
0 2020-01-01
425-
1 NaT
426-
dtype: object
427-
428-
>>> s.dt.date <= datetime.date(2024, 1, 1)
429-
0 True
430-
1 False
431-
dtype: bool
432-
"""
433-
434-
from pandas import Series
435-
import datetime
436-
437-
values = self._get_values()
438-
as_dates = values.to_pydatetime()
439-
440-
def extract_date(x):
441-
return x.date() if isinstance(x, datetime.datetime) else pd.NaT
442-
443-
result = [extract_date(v) for v in as_dates]
444-
445-
return Series(result, index=self._parent.index, name=self._parent.name, dtype=object).__finalize__(self._parent)
446402

447403
def isocalendar(self) -> DataFrame:
448404
"""

pandas/tests/series/indexing/test_datetime.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -498,8 +498,10 @@ def test_dt_date_dtype_all_nat_is_object():
498498
s = pd.Series([pd.NaT, pd.NaT])
499499
s = pd.to_datetime(s)
500500
result = s.dt.date
501-
assert result.dtype == object
502-
assert result.isna().all()
501+
502+
expected = pd.Series([pd.NaT, pd.NaT], dtype=object)
503+
504+
tm.assert_series_equal(result, expected)
503505

504506
def test_dt_date_all_nat_le_date():
505507
#All-NaT Series should not raise error when compared to a datetime.date

0 commit comments

Comments
 (0)