Skip to content

Commit f930102

Browse files
committed
Fix pandas-dev#59772: tz_aware NaT raises exception on to_numpy
Pandas series with NaT (not a time) localized, raised an exception when converting to a numpy array Fixed by removing localization from the NaT's
1 parent dc8401a commit f930102

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

Diff for: doc/source/whatsnew/v3.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -808,6 +808,7 @@ ExtensionArray
808808
^^^^^^^^^^^^^^
809809
- Bug in :class:`Categorical` when constructing with an :class:`Index` with :class:`ArrowDtype` (:issue:`60563`)
810810
- Bug in :meth:`.arrays.ArrowExtensionArray.__setitem__` which caused wrong behavior when using an integer array with repeated values as a key (:issue:`58530`)
811+
. Bug in :meth:`ExtensionArray.to_numpy`` raising ``TypeError`` on a tz-aware series with ``NaT``. (:issue:`59772`)
811812
- Bug in :meth:`ArrowExtensionArray.factorize` where NA values were dropped when input was dictionary-encoded even when dropna was set to False(:issue:`60567`)
812813
- Bug in :meth:`api.types.is_datetime64_any_dtype` where a custom :class:`ExtensionDtype` would return ``False`` for array-likes (:issue:`57055`)
813814
- Bug in comparison between object with :class:`ArrowDtype` and incompatible-dtyped (e.g. string vs bool) incorrectly raising instead of returning all-``False`` (for ``==``) or all-``True`` (for ``!=``) (:issue:`59505`)

Diff for: pandas/core/arrays/base.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -592,7 +592,17 @@ def to_numpy(
592592
-------
593593
numpy.ndarray
594594
"""
595-
result = np.asarray(self, dtype=dtype)
595+
if dtype == "datetime64" and self.dtype.kind == "M":
596+
# Make sure NaT is not tz_aware
597+
result = np.array(
598+
[
599+
np.datetime64("NaT", "s") if isna(x) else x.tz_localize(None).asm8
600+
for x in self
601+
],
602+
dtype="datetime64[s]",
603+
)
604+
else:
605+
result = np.asarray(self, dtype=dtype)
596606
if copy or na_value is not lib.no_default:
597607
result = result.copy()
598608
if na_value is not lib.no_default:

Diff for: pandas/tests/arrays/test_datetimelike.py

+7
Original file line numberDiff line numberDiff line change
@@ -1356,3 +1356,10 @@ def test_from_pandas_array(dtype):
13561356
result = idx_cls(arr)
13571357
expected = idx_cls(data)
13581358
tm.assert_index_equal(result, expected)
1359+
1360+
1361+
def test_to_numpy_with_NaT_tz_aware():
1362+
# GH#59772
1363+
result = pd.Series(NaT).dt.tz_localize("UTC").to_numpy("datetime64")
1364+
expected = pd.Series(NaT).to_numpy("datetime64")
1365+
tm.assert_equal(result, expected)

0 commit comments

Comments
 (0)