Thanks to visit codestin.com
Credit goes to github.com

Skip to content

BUG: timedelta64 with ns units converts to python int rather than a python timedelta #28596

Open
@mdsmarte

Description

@mdsmarte

Describe the issue:

When converting a timedelta64 with nanosecond units to a python timedelta object, the result unexpectedly has the int type. With microsecond (or coarser) units the results is a python timedelta object, as expected.

Instead of silently generating an object with an int type, I would have expected:

  • A timedelta object with the nanosecond resolution dropped (since timedelta only supports microsecond resolution), perhaps with a warning emitted.
  • An error.

Reproduce the code example:

>>> import numpy as np
>>> obj = np.timedelta64(1, "ns")
>>> from datetime import timedelta                      
>>> type(obj.astype("timedelta64[us]").astype(timedelta))
<class 'datetime.timedelta'>
>>> type(obj.astype("timedelta64[ns]").astype(timedelta))
<class 'int'>
>>> type(obj.astype(timedelta))
<class 'int'>

Error message:

Python and NumPy Versions:

1.23.5
3.11.11 |Enthought, Inc. (x86_64)| (default, Mar 26 2025, 11:29:43) [Clang 15.0.0 (clang-1500.1.0.2.5)]

Runtime Environment:

No response

Context for the issue:

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions