[Numpy-discussion] just the date part of a datetime64[s]?
Mark Wiebe
mwwiebe@gmail....
Wed Feb 8 20:48:02 CST 2012
Converting between date and datetime requires caution, because it depends
on your time zone. Because all datetime64's are internally stored in UTC,
simply casting as in your example treats it in UTC. The 'astype' function
does not raise an error to tell you that this is problematic, because
NumPy's default casting for that function has no error policy (yet).
Here's the trouble you can get into:
x = datetime64('2012-02-02 22:00:00', 's')
x.astype('M8[D]')
Out[19]: numpy.datetime64('2012-02-03')
The trouble happens the other way too, because a date is represented as
midnight UTC. This would also raise an exception, but for the fact that
astype does no checking:
x = datetime64('2012-02-02')
x.astype('M8[m]')
Out[23]: numpy.datetime64('2012-02-01T16:00-0800')
The intention is to have functions which handles this casting explicitly,
called datetime_as_date and date_as_datetime. They would take a timezone
parameter, so the code explicitly specifies how the conversion takes place.
A crude replacement for now is:
x = datetime64('2012-02-02 22:00:00', 's')
np.datetime64(np.datetime_as_string(x, timezone='local')[:10])
Out[21]: numpy.datetime64('2012-02-02')
This is hackish, but it should do what you want.
-Mark
On Wed, Feb 8, 2012 at 9:10 AM, John Salvatier <jsalvati@u.washington.edu>wrote:
>
> Hello, is there a good way to get just the date part of a datetime64?
> Frequently datetime datatypes have month(), date(), hour(), etc functions
> that pull out part of the datetime, but I didn't see those mentioned in the
> datetime64 docs. Casting to a 'D' dtype didn't work as I would have hoped:
>
> In [30]: x= datetime64('2012-02-02 09:00:00', 's')
>
> In [31]: x
> Out[31]: numpy.datetime64('2012-02-02T09:00:00-0800')
>
> In [32]: x.astype('datetime64[D]').astype('datetime64[s]')
> Out[32]: numpy.datetime64('2012-02-01T16:00:00-0800')
>
> What's the simplest way to do this?
>
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20120208/0eb6bf08/attachment.html
More information about the NumPy-Discussion
mailing list