Reputation: 111
I know that we can create a single string to np.datetime64
format such as:
a = np.datetime64('2020-01-01')
But what if we have a list with multiple strings of dates in it?
How are we able to apply the same np.datetime64
to convert all the elements inside into a datetime format? Apart from doing a for-loop perhaps.
Upvotes: 1
Views: 4085
Reputation: 31011
When you have your string list, use it as a source to a Numpy array, passing datetime64 as dtype. E.g.:
lst = ['2020-01-01', '2020-02-05', '2020-03-07' ]
a = np.array(lst, dtype='datetime64')
When you execute a
(actually print this array in a notebook),
you will get:
array(['2020-01-01', '2020-02-05', '2020-03-07'], dtype='datetime64[D]')
As you can see, in this case the default precision is Day.
But you can pass the precision explicitely, e.g. b = np.array(lst, dtype='datetime64[s]')
.
Don't be misled by apostrophes surrounding each element in the above
printout, they are not strings. To check it, execute a[0]
and
you will get:
numpy.datetime64('2020-01-01')
Upvotes: 2
Reputation: 16
Using list comprehension:
strings_list= [...]
npdate_list = [np.datetime64(x) for x in strings_list]
Is there a specific reason for you to want to avoid a loop?
List comprehension is okay?
Upvotes: 0