How to convert numpy datetime64 into datetime

85,686

Solution 1

Borrowing from Converting between datetime, Timestamp and datetime64

In [220]: x
Out[220]: numpy.datetime64('2012-06-17T23:00:05.453000000-0700')

In [221]: datetime.datetime.utcfromtimestamp(x.tolist()/1e9)
Out[221]: datetime.datetime(2012, 6, 18, 6, 0, 5, 452999)

Accounting for timezones I think that's right. Looks rather clunky though.

Using int() is more explicit (I think) than tolist()):

In [294]: datetime.datetime.utcfromtimestamp(int(x)/1e9)
Out[294]: datetime.datetime(2012, 6, 18, 6, 0, 5, 452999)

or to get datetime in local:

In [295]: datetime.datetime.fromtimestamp(x.astype('O')/1e9)

But in the test_datatime.py file https://github.com/numpy/numpy/blob/master/numpy/core/tests/test_datetime.py

I find some other options - first convert the general datetime64 to one of the format that specifies units:

In [296]: x.astype('M8[D]').astype('O')
Out[296]: datetime.date(2012, 6, 18)

In [297]: x.astype('M8[ms]').astype('O')
Out[297]: datetime.datetime(2012, 6, 18, 6, 0, 5, 453000)

This works for arrays:

In [303]: np.array([[x,x],[x,x]],dtype='M8[ms]').astype('O')[0,1]
Out[303]: datetime.datetime(2012, 6, 18, 6, 0, 5, 453000)

Solution 2

Note that Timestamp IS a sub-class of datetime.datetime so the [4] will generally work

In [4]: pd.Timestamp(np.datetime64('2012-06-18T02:00:05.453000000-0400'))
Out[4]: Timestamp('2012-06-18 06:00:05.453000')

In [5]: pd.Timestamp(np.datetime64('2012-06-18T02:00:05.453000000-0400')).to_pydatetime()
Out[5]: datetime.datetime(2012, 6, 18, 6, 0, 5, 453000)
Share:
85,686
user6396
Author by

user6396

Updated on July 27, 2022

Comments

  • user6396
    user6396 almost 2 years

    I basically face the same problem posted here:Converting between datetime, Timestamp and datetime64

    but I couldn't find satisfying answer from it, my question how to extract datetime from numpy.datetime64 type:

    if I try:

    np.datetime64('2012-06-18T02:00:05.453000000-0400').astype(datetime.datetime)
    

    it gave me: 1339999205453000000L

    my current solution is convert datetime64 into a string and then turn to datetime again. but it seems quite a silly method.