Skip to content

Commit e3e2f0d

Browse files
committed
REF: move cases out of convert_to_timedelta64
1 parent 1c0defa commit e3e2f0d

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

pandas/_libs/tslibs/timedeltas.pyx

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -419,27 +419,39 @@ def array_to_timedelta64(
419419
try:
420420
if checknull_with_nat_and_na(item):
421421
ival = NPY_NAT
422+
422423
elif cnp.is_timedelta64_object(item):
423424
td64ns_obj = ensure_td64ns(item)
424425
ival = cnp.get_timedelta64_value(td64ns_obj)
426+
427+
elif isinstance(item, _Timedelta):
428+
if item._creso != NPY_FR_ns:
429+
ival = item.as_unit("ns")._value
430+
else:
431+
ival = item._value
432+
433+
elif PyDelta_Check(item):
434+
# i.e. isinstance(item, timedelta)
435+
ival = delta_to_nanoseconds(item)
436+
425437
elif isinstance(item, str):
426438
if (
427439
(len(item) > 0 and item[0] == "P")
428440
or (len(item) > 1 and item[:2] == "-P")
429441
):
430-
item = parse_iso_format_string(item)
442+
ival = parse_iso_format_string(item)
431443
else:
432-
item = parse_timedelta_string(item)
433-
td64ns_obj = np.timedelta64(item, "ns")
434-
ival = cnp.get_timedelta64_value(td64ns_obj)
444+
ival = parse_timedelta_string(item)
445+
435446
elif is_tick_object(item):
436447
ival = item.nanos
448+
437449
elif is_integer_object(item) or is_float_object(item):
438-
td64ns_obj = _numeric_to_td64ns(item, unit)
450+
td64ns_obj = _numeric_to_td64ns(item, parsed_unit)
439451
ival = cnp.get_timedelta64_value(td64ns_obj)
452+
440453
else:
441-
td64ns_obj = convert_to_timedelta64(item, parsed_unit)
442-
ival = cnp.get_timedelta64_value(td64ns_obj)
454+
raise TypeError(f"Invalid type for timedelta scalar: {type(item)}")
443455

444456
except ValueError as err:
445457
if errors == "coerce":

0 commit comments

Comments
 (0)