Unable to populate numpy datetime64 array

I am trying to create a numpy array that will subsequently be populated with some datetime values. I can’t make it work, could you help?

import numpy as np t = np.empty(3,dtype='datetime64') t 

I get a TypeError: Invalid datetime unit "generic" in metadata . Same thing if I try:

 import numpy as np t = np.empty(3,dtype='datetime64') t[0] = np.datetime64('2014-12-12 20:20:20') 

I get:

TypeError: cannot impose a numpy timedelta64 scalar from metadata [m] according to the rule 'same_kind'.

Thanks in advance for your help!

+5
source share
1 answer

It should work if you also specify the unit of time parameter when creating the array. For instance:

 >>> t = np.empty(3, dtype='datetime64[s]') >>> t array(['1970-01-01T00:00:00+0000', '1970-01-01T00:00:00+0000', '1970-01-01T00:00:00+0000'], dtype='datetime64[s]') 

And then you can also assign values ​​as needed:

 >>> t[0] = np.datetime64('2014-12-12 20:20:20') >>> t array(['2014-12-12T20:20:20+0000', '1970-01-01T00:00:00+0000', '1970-01-01T00:00:00+0000'], dtype='datetime64[s]') 

NumPy does not allow the presentation of data with unit units (i.e. no units). Creating an array t without the unit parameter, and then trying to access the first element t[0] will result in this error:

 ValueError: Cannot convert a NumPy datetime value other than NaT with generic units 

Here, NumPy cannot determine which units should have a date and time representation. Guessing can lead to erroneous values, given the different durations of calendar months and years.

This point is not very explicit in the documentation, but it can be gleaned from the datetime page and is noted in the source code here .

+5
source

Source: https://habr.com/ru/post/1208998/


All Articles