Skip to content

REF: simplify DTA.__init__ #47574

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 1 commit into from
Jul 1, 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
23 changes: 10 additions & 13 deletions pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ def _scalar_type(self) -> type[Timestamp]:
_freq = None

def __init__(
self, values, dtype=DT64NS_DTYPE, freq=lib.no_default, copy: bool = False
self, values, dtype=None, freq=lib.no_default, copy: bool = False
) -> None:
values = extract_array(values, extract_numpy=True)
if isinstance(values, IntegerArray):
Expand All @@ -276,22 +276,19 @@ def __init__(
freq = to_offset(freq)
freq, _ = dtl.validate_inferred_freq(freq, values.freq, False)

# validation
dtz = getattr(dtype, "tz", None)
if dtz and values.tz is None:
dtype = DatetimeTZDtype(tz=dtype.tz)
elif dtz and values.tz:
if not timezones.tz_compare(dtz, values.tz):
msg = (
"Timezone of the array and 'dtype' do not match. "
f"'{dtz}' != '{values.tz}'"
if dtype is not None:
dtype = pandas_dtype(dtype)
if not is_dtype_equal(dtype, values.dtype):
raise TypeError(
f"dtype={dtype} does not match data dtype {values.dtype}"
)
raise TypeError(msg)
elif values.tz:
dtype = values.dtype

dtype = values.dtype
values = values._ndarray

elif dtype is None:
dtype = DT64NS_DTYPE

if not isinstance(values, np.ndarray):
raise ValueError(
f"Unexpected type '{type(values).__name__}'. 'values' must be a "
Expand Down
9 changes: 8 additions & 1 deletion pandas/tests/arrays/datetimes/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,16 @@ def test_mismatched_timezone_raises(self):
dtype=DatetimeTZDtype(tz="US/Central"),
)
dtype = DatetimeTZDtype(tz="US/Eastern")
with pytest.raises(TypeError, match="Timezone of the array"):
msg = r"dtype=datetime64\[ns.*\] does not match data dtype datetime64\[ns.*\]"
with pytest.raises(TypeError, match=msg):
DatetimeArray(arr, dtype=dtype)

# also with mismatched tzawareness
with pytest.raises(TypeError, match=msg):
DatetimeArray(arr, dtype=np.dtype("M8[ns]"))
with pytest.raises(TypeError, match=msg):
DatetimeArray(arr.tz_localize(None), dtype=arr.dtype)

def test_non_array_raises(self):
with pytest.raises(ValueError, match="list"):
DatetimeArray([1, 2, 3])
Expand Down