4

I am working with some data that has the date in the format 2017.08333. In the process of converting this to datetime objects I got an error when trying to convert the integer years to datetime.

np.datetime64(['2017','2018'])

The above fails with the error:Could not convert object to NumPy datetime

I was under the impression numpy functions were vectorized. Can someone explain why this doesn't work and how I can solve this? I have 3,000 dates to convert so something that doesn't involve a loop is ideal.

3 Answers 3

7

To create an array of dates, you could do:

import numpy as np

print(np.array(['2018', '2017'], dtype=np.datetime64))

Output

['2018' '2017']

A more detailed explanation can be found here

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

2 Comments

Thanks, so much. I spent so much time trying to figure this out.
btw, use dtype='M8[something_like_Y_or_D_or_s]' if numpy cannot recognize the unit
2

Some of them are. I'm not sure what your input looks like (list or np.array), but you could do something like

np.array(['2017', '2018'], dtype=np.datetime64)

or

my_np_array.astype(np.datetime64)

1 Comment

Wow, thanks. I have been grinding my gears for a while. I feel a little dumb for how easy this was.
0

You can use map as additional too:

>>> import numpy as np
>>> np.array(list(map(np.datetime64,['2017', '2018'])))
array(['2017', '2018'], dtype='datetime64[Y]')

Comments

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.