Skip to content

Commit 41f7f80

Browse files
committed
FIX: DatetimeIndex.array should return DatetimeArray instead of ExtensionArray
- Override array property in DatetimeIndex to return DatetimeArray - Add test case to verify the correct type is returned - Fixes issue where type checkers incorrectly identified return type
1 parent c38b6a3 commit 41f7f80

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

pandas-stubs/core/indexes/datetimes.pyi

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ from pandas import (
2020
TimedeltaIndex,
2121
Timestamp,
2222
)
23+
from pandas.core.arrays import DatetimeArray
2324
from pandas.core.indexes.accessors import DatetimeIndexProperties
2425
from pandas.core.indexes.datetimelike import DatetimeTimedeltaMixin
2526
from pandas.core.series import (
@@ -61,6 +62,11 @@ class DatetimeIndex(
6162
name: Hashable = ...,
6263
) -> Self: ...
6364
def __reduce__(self): ...
65+
66+
# Override the array property to return DatetimeArray instead of ExtensionArray
67+
@property
68+
def array(self) -> DatetimeArray: ...
69+
6470
# various ignores needed for mypy, as we do want to restrict what can be used in
6571
# arithmetic for these types
6672
@overload # type: ignore[override]

tests/indexes/test_indexes.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
import pandas as pd
1515
from pandas.core.arrays.categorical import Categorical
1616
from pandas.core.indexes.base import Index
17+
from pandas.core.arrays import DatetimeArray
18+
from typing import assert_type
1719
from typing_extensions import (
1820
Never,
1921
assert_type,
@@ -1516,3 +1518,15 @@ def test_period_index_asof_locs() -> None:
15161518
assert_type(idx.asof_locs(where, mask), np_1darray[np.intp]),
15171519
np_1darray[np.intp],
15181520
)
1521+
1522+
1523+
def test_datetime_index_array_property():
1524+
"""Test that DatetimeIndex.array returns DatetimeArray instead of ExtensionArray."""
1525+
# Test with to_datetime
1526+
arr = pd.to_datetime(["2020-01-01", "2020-01-02"]).array
1527+
assert_type(arr, DatetimeArray)
1528+
1529+
# Test with DatetimeIndex directly
1530+
dt_index = pd.DatetimeIndex(["2020-01-01", "2020-01-02"])
1531+
assert_type(dt_index.array, DatetimeArray)
1532+

0 commit comments

Comments
 (0)