4

I tried to build a structured array with a datetime coloumn

import numpy as np
na_trades = np.zeros(2, dtype = 'datetime64,i4')
na_trades[0] = (np.datetime64('1970-01-01 00:00:00'),0)

TypeError: Cannot cast NumPy timedelta64 scalar from metadata [s] to  according to the rule 'same_kind'

Is there a way to fix this?

2 Answers 2

4

You have to specify that the datetime64 is in seconds when you create the array because the one you parse and try to assign is a datetime64[s]:

na_trades = np.zeros(2, dtype='datetime64[s],i4')
na_trades[0] = (np.datetime64('1971-01-01 00:00:00'), 0)

The error you get means that the datetime64 object that you specified is not same_kind as the one you try to assing. You try to assign a seconds resolution one, and you created a different one when you constructed the array (by default I think it's nanoseconds).

Sign up to request clarification or add additional context in comments.

2 Comments

What versin of NumPy do you use? it works perfectly for me with NumPy 1.7.1.
In 1.6.2, it raises ValueError. In 1.7.1, it work perfect. I'm sorry.
2

Try following:

>>> na_trades = np.zeros(2, dtype=[('dt', 'datetime64[s]'), ('vol', 'i4')])
>>> na_trades
array([(datetime.datetime(1970, 1, 1, 0, 0), 0),
       (datetime.datetime(1970, 1, 1, 0, 0), 0)], 
      dtype=[('dt', ('<M8[s]', {})), ('vol', '<i4')])
>>> na_trades[0] = (np.datetime64('1970-01-02 00:00:00'),1)
>>> na_trades
array([(datetime.datetime(4707, 11, 29, 0, 0), 1),
       (datetime.datetime(1970, 1, 1, 0, 0), 0)], 
      dtype=[('dt', ('<M8[s]', {})), ('vol', '<i4')])

2 Comments

Actually on 1.7.1 your code raises the exception TypeError: Cannot cast NumPy timedelta64 scalar from metadata [s] to according to the rule 'same_kind' You should update to a new version because the old style of managing datetimes is obsolete in the 1.7.x version of NumPy docs
@ViktorKerkez, I updated the code and confirmed that it work on 1.7.1. Thank you for comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.