I have a datetime index in pandas
index = np.array(['2013-11-11T12:36:00.078757888-0800',
'2013-11-11T12:36:03.692692992-0800',
'2013-11-11T12:36:07.085489920-0800',
'2013-11-11T12:36:08.957488128-0800'], dtype='datetime64[ns]')
I want to calculate the time difference in seconds. The way I came up with is:
diff(index).astype('float64')/1e9
is there a better/cleaner way?
After that, You can create datetime64 format using the numpy. datetime64() format. To convert it to datetime format then you have to use astype() method and just pass the datetime as an argument.
Starting in NumPy 1.7, there are core array data types which natively support datetime functionality. The data type is called datetime64 , so named because datetime is already taken by the Python standard library.
datetime64() method, we can get the date in a numpy array in a particular format i.e year-month-day by using numpy. datetime64() method. Syntax : numpy.datetime64(date) Return : Return the date in a format 'yyyy-mm-dd'.
Your own answer is correct and good. Slightly different way is to specify scale constants with timedelta
expression.
For example, to scale to seconds:
>>> np.diff(index)/np.timedelta64(1, 's')
array([ 3.6139351 , 3.39279693, 1.87199821])
To minutes:
>>> np.diff(index)/np.timedelta64(1, 'm')
array([ 0.06023225, 0.05654662, 0.03119997])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With