[Numpy-discussion] Convert datetime64 to python datetime.datetime in numpy 1.6.1?
Didrik Pinte
dpinte at enthought.com
Sun Dec 4 06:30:07 EST 2011
On Sun, Dec 4, 2011 at 6:11 AM, Warren Weckesser
<warren.weckesser at enthought.com> wrote:
> In numpy 1.6.1, what's the most straightforward way to convert a datetime64
> to a python datetime.datetime? E.g. I have
>
> In [1]: d = datetime64("2011-12-03 12:34:56.75")
>
> In [2]: d
> Out[2]: 2011-12-03 12:34:56.750000
>
> I want the same time as a datetime.datetime instance. My best hack so far
> is to parse repr(d) with datetime.datetime.strptime:
>
> In [3]: import datetime
>
> In [4]: dt = datetime.datetime.strptime(repr(d), "%Y-%m-%d %H:%M:%S.%f")
>
> In [5]: dt
> Out[5]: datetime.datetime(2011, 12, 3, 12, 34, 56, 750000)
>
> That works--unless there are no microseconds, in which case ".%f" must be
> removed from the format string--but there must be a better way.
>
> Warren
Warren,
You can do that :
In [13]: a = array(["2011-12-03 12:34:56.75"], dtype=datetime64)
In [14]: b = a.astype(object)
In [15]: b[0]
Out[15]: datetime.datetime(2011, 12, 3, 12, 34, 56, 750000)
Not sure how efficient it is but it works fine.
-- Didrik
More information about the NumPy-Discussion
mailing list