Skip to content

Commit

Permalink
fix: out-of-bounds datetime.date raises OutOfBoundsDatetime (#180)
Browse files Browse the repository at this point in the history
  • Loading branch information
tswast authored Mar 30, 2023
1 parent a7fc29a commit 4f3399e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
21 changes: 11 additions & 10 deletions db_dtypes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,19 +246,18 @@ def _datetime(
scalar,
match_fn=re.compile(r"\s*(?P<year>\d+)-(?P<month>\d+)-(?P<day>\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:
Expand All @@ -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
Expand Down
2 changes: 2 additions & 0 deletions tests/unit/test_date.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit 4f3399e

Please sign in to comment.