Home > Back-end >  Inserting a datetime value within a datetime array Numpy Python
Inserting a datetime value within a datetime array Numpy Python

Time:01-03

I want to insert the date '2015-12-24 12:51:00' as a datetime value within array as 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']

CodePudding user response:

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

CodePudding user response:

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,

  • Related