Skip to content

BUG/CLN: DatetimeTZDtype.construct_from_string Exception #28505

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 20, 2019
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
19 changes: 11 additions & 8 deletions pandas/core/dtypes/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,7 @@ def __init__(self, unit="ns", tz=None):
tz = timezones.tz_standardize(tz)
elif tz is not None:
raise pytz.UnknownTimeZoneError(tz)
elif tz is None:
if tz is None:
raise TypeError("A 'tz' is required.")

self._unit = unit
Expand Down Expand Up @@ -737,14 +737,17 @@ def construct_from_string(cls, string):
"""
if isinstance(string, str):
msg = "Could not construct DatetimeTZDtype from '{}'"
try:
match = cls._match.match(string)
if match:
d = match.groupdict()
match = cls._match.match(string)
if match:
d = match.groupdict()
try:
return cls(unit=d["unit"], tz=d["tz"])
except Exception:
# TODO(py3): Change this pass to `raise TypeError(msg) from e`
pass
except (KeyError, TypeError, ValueError) as err:
# KeyError if maybe_get_tz tries and fails to get a
# pytz timezone (actually pytz.UnknownTimeZoneError).
# TypeError if we pass a nonsense tz;
# ValueError if we pass a unit other than "ns"
raise TypeError(msg.format(string)) from err
raise TypeError(msg.format(string))

raise TypeError("Could not construct DatetimeTZDtype")
Expand Down
12 changes: 11 additions & 1 deletion pandas/tests/dtypes/test_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,9 +248,19 @@ def test_construct_from_string_raises(self):
with pytest.raises(TypeError, match="notatz"):
DatetimeTZDtype.construct_from_string("datetime64[ns, notatz]")

with pytest.raises(TypeError, match="^Could not construct DatetimeTZDtype$"):
msg = "^Could not construct DatetimeTZDtype"
with pytest.raises(TypeError, match=msg):
# list instead of string
DatetimeTZDtype.construct_from_string(["datetime64[ns, notatz]"])

with pytest.raises(TypeError, match=msg):
# non-nano unit
DatetimeTZDtype.construct_from_string("datetime64[ps, UTC]")

with pytest.raises(TypeError, match=msg):
# dateutil str that returns None from gettz
DatetimeTZDtype.construct_from_string("datetime64[ns, dateutil/invalid]")

def test_is_dtype(self):
assert not DatetimeTZDtype.is_dtype(None)
assert DatetimeTZDtype.is_dtype(self.dtype)
Expand Down