Reputation: 162
I want to insert the date '2015-12-24 12:51:00'
as a datetime value within array a
s first index how would I be able to do that and get to the Expected Output. to the datetime array a
import numpy as np
import datetime
a = np.array(['2017-09-15 07:11:00', '2017-09-15 12:11:00', '2017-12-22 03:26:00',
'2017-12-22 03:56:00', '2017-12-22 20:59:00', '2017-12-24 12:51:00'], dtype='datetime64[ns]')
datetime = np.insert(a, 0, ('2015-12-24 12:51:00',dtype='datetime64[ns]'))
Error message:
File "<ipython-input-5-ac3ba1f95707>", line 6
datetime = np.insert(a, 0, ('2015-12-24 12:51:00',dtype='datetime64[ns]'))
^
SyntaxError: invalid syntax
Expected output:
['2015-12-24T12:51:00.000000000' '2017-09-15T07:11:00.000000000'
'2017-09-15T12:11:00.000000000' '2017-12-22T03:26:00.000000000'
'2017-12-22T03:56:00.000000000' '2017-12-22T20:59:00.000000000'
'2017-12-24T12:51:00.000000000']
Upvotes: 0
Views: 1071
Reputation: 231385
np.array('2015-12-24 12:51:00',dtype='datetime64[ns]')
is the correct syntax for creating a datetime array. dtype
is a keyword parameter for the np.array
function.
There are cases like hstack
where you would want to cast this string to the correct dtype first, but insert
does take care of that for you. It has a line:
values = array(values, copy=False, ndmin=arr.ndim, dtype=arr.dtype)
Certainly no harm in doing the conversion yourself, just use the correct syntax.
Upvotes: 0
Reputation: 216
You do not need to specify dtype
on insert
, that is basically what the error you get is saying. Just do np.insert(a, 0, ('2015-12-24 12:51:00'))
source: https://numpy.org/doc/stable/reference/generated/numpy.insert.html
Upvotes: 1