2 views
in Python

How do I convert a numpy.datetime64 object to a datetime.datetime (or Timestamp)?

In the following code, I create a datetime, timestamp and datetime64 objects.

import datetime

import numpy as np

import pandas as pd

dt = datetime.datetime(2012, 5, 1)

# A strange way to extract a Timestamp object, there's surely a better way?

ts = pd.DatetimeIndex([dt])

dt64 = np.datetime64(dt)

In : dt

Out: datetime.datetime(2012, 5, 1, 0, 0)

In : ts

Out: <Timestamp: 2012-05-01 00:00:00>

In : dt64

Out: numpy.datetime64('2012-05-01T01:00:00.000000+0100')

Note: it's easy to get the datetime from the Timestamp:

In : ts.to_datetime()

Out: datetime.datetime(2012, 5, 1, 0, 0)

But how do we extract the datetime or Timestamp from a numpy.datetime64 (dt64)?

Update: a somewhat nasty example in my dataset (perhaps the motivating example) seems to be:

dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100')

which should be datetime.datetime(2002, 6, 28, 1, 0), and not a long (!) (1025222400000000000L)...

by (106k points)

To convert between datetime, timestamp and datetime64 you can use the below-mentioned code:-

>>> from datetime import datetime

>>> import numpy as np

>>> dt = datetime.utcnow()

>>> dt

datetime.datetime(2012, 12, 4, 19, 51, 25, 362455)

>>> dt64 = np.datetime64(dt)

>>> ts = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')

>>> ts

1354650685.3624549

>>> datetime.utcfromtimestamp(ts)

datetime.datetime(2012, 12, 4, 19, 51, 25, 362455)

>>> np.__version__

'1.8.0.dev-7b75899'