diff --git a/db_dtypes/__init__.py b/db_dtypes/__init__.py index 3ecefed..54721a3 100644 --- a/db_dtypes/__init__.py +++ b/db_dtypes/__init__.py @@ -246,19 +246,18 @@ def _datetime( scalar, match_fn=re.compile(r"\s*(?P\d+)-(?P\d+)-(?P\d+)\s*$").match, ) -> Optional[numpy.datetime64]: - if isinstance(scalar, numpy.datetime64): - return scalar - # Convert pyarrow values to datetime.date. if isinstance(scalar, (pyarrow.Date32Scalar, pyarrow.Date64Scalar)): scalar = scalar.as_py() if pandas.isna(scalar): return numpy.datetime64("NaT") + elif isinstance(scalar, numpy.datetime64): + dateObj = pandas.Timestamp(scalar) elif isinstance(scalar, datetime.date): - return pandas.Timestamp( + dateObj = pandas.Timestamp( year=scalar.year, month=scalar.month, day=scalar.day - ).to_datetime64() + ) elif isinstance(scalar, str): match = match_fn(scalar) if not match: @@ -272,14 +271,16 @@ def _datetime( month=month, day=day, ) - if pandas.Timestamp.min < dateObj < pandas.Timestamp.max: - return dateObj.to_datetime64() - else: # pragma: NO COVER - # TODO(#166): Include these lines in coverage when pandas 2.0 is released. - raise OutOfBoundsDatetime("Out of bounds", scalar) # pragma: NO COVER else: raise TypeError("Invalid value type", scalar) + # TODO(#64): Support larger ranges with other units. + if pandas.Timestamp.min < dateObj < pandas.Timestamp.max: + return dateObj.to_datetime64() + else: # pragma: NO COVER + # TODO(#166): Include these lines in coverage when pandas 2.0 is released. + raise OutOfBoundsDatetime("Out of bounds", scalar) # pragma: NO COVER + def _box_func(self, x): if pandas.isna(x): return pandas.NaT diff --git a/tests/unit/test_date.py b/tests/unit/test_date.py index 5bd0812..fddf1a0 100644 --- a/tests/unit/test_date.py +++ b/tests/unit/test_date.py @@ -159,6 +159,8 @@ def test_date_parsing_errors(value, error): ("9999-12-31", "Out of bounds"), ("1677-09-21", "Out of bounds"), ("2262-04-12", "Out of bounds"), + (datetime.date(1, 1, 1), "Out of bounds"), + (datetime.date(9999, 12, 31), "Out of bounds"), ], ) def test_date_parsing_errors_out_of_bounds(value, error):