Skip to content

Commit

Permalink
Switch .dt to raise an AttributeError (#8724)
Browse files Browse the repository at this point in the history
* Switch `.dt` to raise an `AttributeError`

Discussion at #8718

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
max-sixty and pre-commit-ci[bot] authored Feb 9, 2024
1 parent db680b0 commit 97c8c18
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
3 changes: 3 additions & 0 deletions doc/whats-new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ Documentation
Internal Changes
~~~~~~~~~~~~~~~~

- ``DataArray.dt`` now raises an ``AttributeError`` rather than a ``TypeError``
when the data isn't datetime-like. (:issue:`8718`, :pull:`8724`)
By `Maximilian Roos <https://github.com/max-sixty>`_.

.. _whats-new.2024.01.1:

Expand Down
6 changes: 5 additions & 1 deletion xarray/core/accessor_dt.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,11 @@ def __new__(cls, obj: T_DataArray) -> CombinedDatetimelikeAccessor:
# appropriate. Since we're checking the dtypes anyway, we'll just
# do all the validation here.
if not _contains_datetime_like_objects(obj.variable):
raise TypeError(
# We use an AttributeError here so that `obj.dt` raises an error that
# `getattr` expects; https://github.com/pydata/xarray/issues/8718. It's a
# bit unusual in a `__new__`, but that's the only case where we use this
# class.
raise AttributeError(
"'.dt' accessor only available for "
"DataArray with datetime64 timedelta64 dtype or "
"for arrays containing cftime datetime "
Expand Down
4 changes: 2 additions & 2 deletions xarray/tests/test_accessor_dt.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def test_not_datetime_type(self) -> None:
nontime_data = self.data.copy()
int_data = np.arange(len(self.data.time)).astype("int8")
nontime_data = nontime_data.assign_coords(time=int_data)
with pytest.raises(TypeError, match=r"dt"):
with pytest.raises(AttributeError, match=r"dt"):
nontime_data.time.dt

@pytest.mark.filterwarnings("ignore:dt.weekofyear and dt.week have been deprecated")
Expand Down Expand Up @@ -310,7 +310,7 @@ def test_not_datetime_type(self) -> None:
nontime_data = self.data.copy()
int_data = np.arange(len(self.data.time)).astype("int8")
nontime_data = nontime_data.assign_coords(time=int_data)
with pytest.raises(TypeError, match=r"dt"):
with pytest.raises(AttributeError, match=r"dt"):
nontime_data.time.dt

@pytest.mark.parametrize(
Expand Down

0 comments on commit 97c8c18

Please sign in to comment.