How do I convert a numpy.datetime64
object to a datetime.datetime
(or Timestamp
)?
In the following code, I create a datetime,
This post has been up for 4 years and I still struggled with this conversion problem - so the issue is still active in 2017 in some sense. I was somewhat shocked that the numpy documentation does not readily offer a simple conversion algorithm but that's another story.
I have come across another way to do the conversion that only involves modules numpy
and datetime
, it does not require pandas to be imported which seems to me to be a lot of code to import for such a simple conversion. I noticed that datetime64.astype(datetime.datetime)
will return a datetime.datetime
object if the original datetime64
is in micro-second units while other units return an integer timestamp. I use module xarray
for data I/O from Netcdf files which uses the datetime64
in nanosecond units making the conversion fail unless you first convert to micro-second units. Here is the example conversion code,
import numpy as np
import datetime
def convert_datetime64_to_datetime( usert: np.datetime64 )->datetime.datetime:
t = np.datetime64( usert, 'us').astype(datetime.datetime)
return t
Its only tested on my machine, which is Python 3.6 with a recent 2017 Anaconda distribution. I have only looked at scalar conversion and have not checked array based conversions although I'm guessing it will be good. Nor have I looked at the numpy datetime64 source code to see if the operation makes sense or not.