Skip to content

BUG: DatetimeIndex ignoring explicit tz=None #48659

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 2 commits into from
Sep 21, 2022
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.6.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ Categorical
Datetimelike
^^^^^^^^^^^^
- Bug in :func:`pandas.infer_freq`, raising ``TypeError`` when inferred on :class:`RangeIndex` (:issue:`47084`)
-
- Bug in :class:`DatetimeIndex` constructor failing to raise when ``tz=None`` is explicitly specified in conjunction with timezone-aware ``dtype`` or data (:issue:`48659`)

Timedelta
^^^^^^^^^
Expand Down
24 changes: 19 additions & 5 deletions pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ def _from_sequence_not_strict(
data,
dtype=None,
copy: bool = False,
tz=None,
tz=lib.no_default,
freq: str | BaseOffset | lib.NoDefault | None = lib.no_default,
dayfirst: bool = False,
yearfirst: bool = False,
Expand Down Expand Up @@ -1984,7 +1984,7 @@ def _sequence_to_dt64ns(
data,
dtype=None,
copy: bool = False,
tz=None,
tz=lib.no_default,
dayfirst: bool = False,
yearfirst: bool = False,
ambiguous="raise",
Expand Down Expand Up @@ -2021,14 +2021,17 @@ def _sequence_to_dt64ns(
------
TypeError : PeriodDType data is passed
"""
explicit_tz_none = tz is None
if tz is lib.no_default:
tz = None

inferred_freq = None

dtype = _validate_dt64_dtype(dtype)
tz = timezones.maybe_get_tz(tz)

# if dtype has an embedded tz, capture it
tz = validate_tz_from_dtype(dtype, tz)
tz = validate_tz_from_dtype(dtype, tz, explicit_tz_none)

data, copy = dtl.ensure_arraylike_for_datetimelike(
data, copy, cls_name="DatetimeArray"
Expand Down Expand Up @@ -2124,7 +2127,12 @@ def _sequence_to_dt64ns(
assert result.dtype == "M8[ns]", result.dtype

# We have to call this again after possibly inferring a tz above
validate_tz_from_dtype(dtype, tz)
validate_tz_from_dtype(dtype, tz, explicit_tz_none)
if tz is not None and explicit_tz_none:
raise ValueError(
"Passed data is timezone-aware, incompatible with 'tz=None'. "
"Use obj.tz_localize(None) instead."
)

return result, tz, inferred_freq

Expand Down Expand Up @@ -2366,7 +2374,9 @@ def _validate_dt64_dtype(dtype):
return dtype


def validate_tz_from_dtype(dtype, tz: tzinfo | None) -> tzinfo | None:
def validate_tz_from_dtype(
dtype, tz: tzinfo | None, explicit_tz_none: bool = False
) -> tzinfo | None:
"""
If the given dtype is a DatetimeTZDtype, extract the implied
tzinfo object from it and check that it does not conflict with the given
Expand All @@ -2376,6 +2386,8 @@ def validate_tz_from_dtype(dtype, tz: tzinfo | None) -> tzinfo | None:
----------
dtype : dtype, str
tz : None, tzinfo
explicit_tz_none : bool, default False
Whether tz=None was passed explicitly, as opposed to lib.no_default.

Returns
-------
Expand All @@ -2399,6 +2411,8 @@ def validate_tz_from_dtype(dtype, tz: tzinfo | None) -> tzinfo | None:
if dtz is not None:
if tz is not None and not timezones.tz_compare(tz, dtz):
raise ValueError("cannot supply both a tz and a dtype with a tz")
elif explicit_tz_none:
raise ValueError("Cannot pass both a timezone-aware dtype and tz=None")
tz = dtz

if tz is not None and is_datetime64_dtype(dtype):
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ def __new__(
cls,
data=None,
freq: str | BaseOffset | lib.NoDefault = lib.no_default,
tz=None,
tz=lib.no_default,
normalize: bool = False,
closed=None,
ambiguous="raise",
Expand All @@ -336,7 +336,7 @@ def __new__(
if (
isinstance(data, DatetimeArray)
and freq is lib.no_default
and tz is None
and tz is lib.no_default
and dtype is None
):
# fastpath, similar logic in TimedeltaIndex.__new__;
Expand All @@ -347,7 +347,7 @@ def __new__(
elif (
isinstance(data, DatetimeArray)
and freq is lib.no_default
and tz is None
and tz is lib.no_default
and is_dtype_equal(data.dtype, dtype)
):
# Reached via Index.__new__ when we call .astype
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/indexes/datetimes/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,21 @@


class TestDatetimeIndex:
def test_explicit_tz_none(self):
# GH#48659
dti = date_range("2016-01-01", periods=10, tz="UTC")

msg = "Passed data is timezone-aware, incompatible with 'tz=None'"
with pytest.raises(ValueError, match=msg):
DatetimeIndex(dti, tz=None)

with pytest.raises(ValueError, match=msg):
DatetimeIndex(np.array(dti), tz=None)

msg = "Cannot pass both a timezone-aware dtype and tz=None"
with pytest.raises(ValueError, match=msg):
DatetimeIndex([], dtype="M8[ns, UTC]", tz=None)

@pytest.mark.parametrize(
"dt_cls", [DatetimeIndex, DatetimeArray._from_sequence_not_strict]
)
Expand Down