Skip to content

Commit e911d97

Browse files
jbrockmendelproost
authored andcommitted
BUG/CLN: DatetimeTZDtype.construct_from_string Exception (pandas-dev#28505)
1 parent 3b42193 commit e911d97

File tree

2 files changed

+22
-9
lines changed

2 files changed

+22
-9
lines changed

pandas/core/dtypes/dtypes.py

+11-8
Original file line numberDiff line numberDiff line change
@@ -685,7 +685,7 @@ def __init__(self, unit="ns", tz=None):
685685
tz = timezones.tz_standardize(tz)
686686
elif tz is not None:
687687
raise pytz.UnknownTimeZoneError(tz)
688-
elif tz is None:
688+
if tz is None:
689689
raise TypeError("A 'tz' is required.")
690690

691691
self._unit = unit
@@ -737,14 +737,17 @@ def construct_from_string(cls, string):
737737
"""
738738
if isinstance(string, str):
739739
msg = "Could not construct DatetimeTZDtype from '{}'"
740-
try:
741-
match = cls._match.match(string)
742-
if match:
743-
d = match.groupdict()
740+
match = cls._match.match(string)
741+
if match:
742+
d = match.groupdict()
743+
try:
744744
return cls(unit=d["unit"], tz=d["tz"])
745-
except Exception:
746-
# TODO(py3): Change this pass to `raise TypeError(msg) from e`
747-
pass
745+
except (KeyError, TypeError, ValueError) as err:
746+
# KeyError if maybe_get_tz tries and fails to get a
747+
# pytz timezone (actually pytz.UnknownTimeZoneError).
748+
# TypeError if we pass a nonsense tz;
749+
# ValueError if we pass a unit other than "ns"
750+
raise TypeError(msg.format(string)) from err
748751
raise TypeError(msg.format(string))
749752

750753
raise TypeError("Could not construct DatetimeTZDtype")

pandas/tests/dtypes/test_dtypes.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -248,9 +248,19 @@ def test_construct_from_string_raises(self):
248248
with pytest.raises(TypeError, match="notatz"):
249249
DatetimeTZDtype.construct_from_string("datetime64[ns, notatz]")
250250

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

256+
with pytest.raises(TypeError, match=msg):
257+
# non-nano unit
258+
DatetimeTZDtype.construct_from_string("datetime64[ps, UTC]")
259+
260+
with pytest.raises(TypeError, match=msg):
261+
# dateutil str that returns None from gettz
262+
DatetimeTZDtype.construct_from_string("datetime64[ns, dateutil/invalid]")
263+
254264
def test_is_dtype(self):
255265
assert not DatetimeTZDtype.is_dtype(None)
256266
assert DatetimeTZDtype.is_dtype(self.dtype)

0 commit comments

Comments
 (0)