Skip to content

Commit c5fc3c6

Browse files
BUG: catch out-of-bounds datetime64 in Series/DataFrame constructor
1 parent 2d2606d commit c5fc3c6

File tree

3 files changed

+10
-2
lines changed

3 files changed

+10
-2
lines changed

pandas/core/dtypes/cast.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1063,7 +1063,7 @@ def maybe_cast_to_datetime(value, dtype, errors='raise'):
10631063
dtype = value.dtype
10641064

10651065
if dtype.kind == 'M' and dtype != _NS_DTYPE:
1066-
value = value.astype(_NS_DTYPE)
1066+
value = tslibs.conversion.ensure_datetime64ns(value)
10671067

10681068
elif dtype.kind == 'm' and dtype != _TD_DTYPE:
10691069
value = to_timedelta(value)

pandas/core/internals/construction.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import numpy.ma as ma
99

1010
from pandas._libs import lib
11-
from pandas._libs.tslibs import IncompatibleFrequency
11+
from pandas._libs.tslibs import IncompatibleFrequency, OutOfBoundsDatetime
1212
from pandas.compat import raise_with_traceback
1313

1414
from pandas.core.dtypes.cast import (
@@ -701,6 +701,9 @@ def _try_cast(arr, take_fast_path, dtype, copy, raise_cast_failure):
701701
elif not is_extension_type(subarr):
702702
subarr = construct_1d_ndarray_preserving_na(subarr, dtype,
703703
copy=copy)
704+
except OutOfBoundsDatetime:
705+
if raise_cast_failure:
706+
raise
704707
except (ValueError, TypeError):
705708
if is_categorical_dtype(dtype):
706709
# We *do* allow casting to categorical, since we know

pandas/tests/series/test_constructors.py

+5
Original file line numberDiff line numberDiff line change
@@ -909,6 +909,11 @@ def test_constructor_with_naive_string_and_datetimetz_dtype(self, arg):
909909
expected = Series(pd.Timestamp(arg)).dt.tz_localize('CET')
910910
assert_series_equal(result, expected)
911911

912+
def test_constructor_datetime64_outofbound(self):
913+
# GH-26206 out of bound non-ns unit
914+
with pytest.raises(pd.errors.OutOfBoundsDatetime):
915+
pd.Series(np.array(['2262-04-12'], dtype='datetime64[D]'))
916+
912917
def test_construction_interval(self):
913918
# construction from interval & array of intervals
914919
index = IntervalIndex.from_breaks(np.arange(3), closed='right')

0 commit comments

Comments
 (0)