Convert dd, mm, yy arrays to numpy datetime

Viewed 182

I am trying to convert separate arrays of YY, MM, DD values to a numpy datetime64 array. Here is the code

import numpy as np

iyy = [2020, 2020, 2019, 2018, 2017]
imm = [2, 4, 4, 6, 8]
idd = [1, 2, 3, 4, 5]

isod = []
for y, m, d in zip(iyy, imm, idd):
    isod.append("%4d-%02d-%02d" % (y, m, d))

t1 = np.datetime64(np.asarray(isod))

This gives the error Could not convert object to NumPy datetime. Would appreciate any suggestions for achieving this. Thanks in advance

2 Answers

Change

np.datetime64(np.asarray(isod))

to

np.asarray(isod).astype(np.datetime64)

Full code:

Try it online!

import numpy as np

iyy = [2020, 2020, 2019, 2018, 2017]
imm = [2, 4, 4, 6, 8]
idd = [1, 2, 3, 4, 5]

isod = []
for y, m, d in zip(iyy, imm, idd):
    isod.append("%4d-%02d-%02d" % (y, m, d))

t1 = np.asarray(isod).astype(np.datetime64)
print(t1)

Output:

['2020-02-01' '2020-04-02' '2019-04-03' '2018-06-04' '2017-08-05']

You could do the conversion to numpy.datetime64 in a list comprehension, then create a numpy.array from that list

>>> np.array([np.datetime64('{:04d}-{:02d}-{:02d}'.format(y, m, d)) for y, m, d in zip(iyy, imm, idd)])
array(['2020-02-01', '2020-04-02', '2019-04-03', '2018-06-04', '2017-08-05'],
      dtype='datetime64[D]')
Related