Skip to content

nanosecond precsion datetime converts to int in stead of datetime #18363

Closed

Description

@feefladder

When converting nanosecond precision np.datetime64 to datetime.datetime, an int is returned, whereas a datetime.datetime would be desireable/expected.

Reproducing code example:

from this SO thread. I also explained it in this xarray issue

import numpy as np

print('second precision')
t = np.datetime64('2000-01-01 00:00:00') 
print(t)
print(t.astype(datetime.datetime))
print(t.item())

print('microsecond precision')
t = np.datetime64('2000-01-01 00:00:00.0000') 
print(t)
print(t.astype(datetime.datetime))
print(t.item())

print('nanosecond precision')
t = np.datetime64('2000-01-01 00:00:00.0000000') 
print(t)
print(t.astype(datetime.datetime))
print(t.item())
import pandas as pd 
print(pd.to_datetime(str(t)))


second precision
2000-01-01T00:00:00
2000-01-01 00:00:00
2000-01-01 00:00:00
microsecond precision
2000-01-01T00:00:00.000000
2000-01-01 00:00:00
2000-01-01 00:00:00
nanosecond precision
2000-01-01T00:00:00.000000000
946684800000000000
946684800000000000
2000-01-01 00:00:00

Error message:

none,

NumPy/Python version information:

numpy 1.20.0
sys:
3.7.9 | packaged by conda-forge | (default, Dec 9 2020, 21:08:20)
[GCC 9.3.0]

Activity

  1. feefladder commented on Feb 8, 2021

    @feefladder
    Author

    In the specifications of datetime:
    it says that conversion to datetime should lose precision or overflow as needed. Not convert to int

    Also note that explicit conversion. i.e.
    t.astype('datetime[us]').astype(datetime.datetime)
    works as expected.

  2. gerritholl commented on Nov 11, 2021

    @gerritholl
    Contributor

    Duplicate of #7619

  3. drf5n commented on Oct 20, 2023

    @drf5n

    In the specifications of datetime: it says that conversion to datetime should lose precision or overflow as needed. Not convert to int

    Also note that explicit conversion. i.e. t.astype('datetime[us]').astype(datetime.datetime) works as expected.

    Maybe this instead:

     t.astype('datetime64[us]').astype(datetime.datetime)
    

    or

    t.astype('datetime64[us]').item()
    

    Either way it's casting the ns precision into a datetime-compatible us precision.

  4. InessaPawson commented on Oct 17, 2026

    @InessaPawson
    Member

    Still reproduces on 2.5.3. The workaround from this thread, t.astype('datetime64[us]').item(), remains the way to go in the meantime.
    Closing as a duplicate of #7619, which tracks the same underlying problem and has the discussion on what the right fix is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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