Skip to content

Commit c228597

Browse files
meeseeksmachinejreback
authored andcommitted
Backport PR #24961: fix+test to_timedelta('NaT', box=False) (#25025)
1 parent e3cc0b1 commit c228597

File tree

3 files changed

+10
-4
lines changed

3 files changed

+10
-4
lines changed

doc/source/whatsnew/v0.24.1.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ Bug Fixes
6666
-
6767

6868
**Timedelta**
69-
69+
- Bug in :func:`to_timedelta` with `box=False` incorrectly returning a ``datetime64`` object instead of a ``timedelta64`` object (:issue:`24961`)
7070
-
7171
-
7272
-

pandas/core/tools/timedeltas.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,8 @@ def _coerce_scalar_to_timedelta_type(r, unit='ns', box=True, errors='raise'):
120120
try:
121121
result = Timedelta(r, unit)
122122
if not box:
123-
result = result.asm8
123+
# explicitly view as timedelta64 for case when result is pd.NaT
124+
result = result.asm8.view('timedelta64[ns]')
124125
except ValueError:
125126
if errors == 'raise':
126127
raise

pandas/tests/scalar/timedelta/test_timedelta.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -309,8 +309,13 @@ def test_iso_conversion(self):
309309
assert to_timedelta('P0DT0H0M1S') == expected
310310

311311
def test_nat_converters(self):
312-
assert to_timedelta('nat', box=False).astype('int64') == iNaT
313-
assert to_timedelta('nan', box=False).astype('int64') == iNaT
312+
result = to_timedelta('nat', box=False)
313+
assert result.dtype.kind == 'm'
314+
assert result.astype('int64') == iNaT
315+
316+
result = to_timedelta('nan', box=False)
317+
assert result.dtype.kind == 'm'
318+
assert result.astype('int64') == iNaT
314319

315320
@pytest.mark.parametrize('units, np_unit',
316321
[(['Y', 'y'], 'Y'),

0 commit comments

Comments
 (0)