Skip to content

Commit 0e20990

Browse files
authored
BUG: fix to_datetime with np.datetime64[ps] giving wrong conversion (#60342)
1 parent 6a7685f commit 0e20990

File tree

3 files changed

+16
-5
lines changed

3 files changed

+16
-5
lines changed

doc/source/whatsnew/v3.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -626,6 +626,7 @@ Datetimelike
626626
- Bug in :meth:`Series.dt.microsecond` producing incorrect results for pyarrow backed :class:`Series`. (:issue:`59154`)
627627
- Bug in :meth:`to_datetime` not respecting dayfirst if an uncommon date string was passed. (:issue:`58859`)
628628
- Bug in :meth:`to_datetime` reports incorrect index in case of any failure scenario. (:issue:`58298`)
629+
- Bug in :meth:`to_datetime` wrongly converts when ``arg`` is a ``np.datetime64`` object with unit of ``ps``. (:issue:`60341`)
629630
- Bug in setting scalar values with mismatched resolution into arrays with non-nanosecond ``datetime64``, ``timedelta64`` or :class:`DatetimeTZDtype` incorrectly truncating those scalars (:issue:`56410`)
630631

631632
Timedelta

pandas/_libs/src/vendored/numpy/datetime/np_datetime.c

+6-5
Original file line numberDiff line numberDiff line change
@@ -660,11 +660,12 @@ void pandas_datetime_to_datetimestruct(npy_datetime dt, NPY_DATETIMEUNIT base,
660660
perday = 24LL * 60 * 60 * 1000 * 1000 * 1000 * 1000;
661661

662662
set_datetimestruct_days(extract_unit(&dt, perday), out);
663-
out->hour = (npy_int32)extract_unit(&dt, 1000LL * 1000 * 1000 * 60 * 60);
664-
out->min = (npy_int32)extract_unit(&dt, 1000LL * 1000 * 1000 * 60);
665-
out->sec = (npy_int32)extract_unit(&dt, 1000LL * 1000 * 1000);
666-
out->us = (npy_int32)extract_unit(&dt, 1000LL);
667-
out->ps = (npy_int32)(dt * 1000);
663+
out->hour =
664+
(npy_int32)extract_unit(&dt, 1000LL * 1000 * 1000 * 1000 * 60 * 60);
665+
out->min = (npy_int32)extract_unit(&dt, 1000LL * 1000 * 1000 * 1000 * 60);
666+
out->sec = (npy_int32)extract_unit(&dt, 1000LL * 1000 * 1000 * 1000);
667+
out->us = (npy_int32)extract_unit(&dt, 1000LL * 1000);
668+
out->ps = (npy_int32)(dt);
668669
break;
669670

670671
case NPY_FR_fs:

pandas/tests/tools/test_to_datetime.py

+9
Original file line numberDiff line numberDiff line change
@@ -3668,3 +3668,12 @@ def test_to_datetime_mixed_awareness_mixed_types(aware_val, naive_val, naive_fir
36683668
to_datetime(vec, format="mixed")
36693669
with pytest.raises(ValueError, match=msg):
36703670
DatetimeIndex(vec)
3671+
3672+
3673+
def test_to_datetime_wrapped_datetime64_ps():
3674+
# GH#60341
3675+
result = to_datetime([np.datetime64(1901901901901, "ps")])
3676+
expected = DatetimeIndex(
3677+
["1970-01-01 00:00:01.901901901"], dtype="datetime64[ns]", freq=None
3678+
)
3679+
tm.assert_index_equal(result, expected)

0 commit comments

Comments
 (0)