Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting seconds from numpy timedelta64

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?

like image 835
Fra Avatar asked Dec 23 '13 06:12

Fra


People also ask

How do I convert datetime64 to datetime?

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.

Does NumPy have datetime?

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.

What is NumPy datetime64?

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'.


1 Answers

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])
like image 156
alko Avatar answered Oct 14 '22 23:10

alko