Suppose you want to calculate the difference between the array t1 and scalar t0 (they can be either arrays or scalars):
In [1]: import numpy as np In [2]: t1=np.arange('2001-01-01T00:00', '2001-01-01T00:05', dtype='datetime64') In [3]: t1 Out[3]: array(['2001-01-01T00:00-0200', '2001-01-01T00:01-0200', '2001-01-01T00:02-0200', '2001-01-01T00:03-0200', '2001-01-01T00:04-0200'], dtype='datetime64[m]') In [4]: t0=np.datetime64('2001-01-01T00:00:00') In [5]: t0 Out[5]: numpy.datetime64('2001-01-01T00:00:00-0200')
The best way to calculate time differences in numpy is to use timedelta64. In the above example, t0 is in minutes and t1 is in seconds. When calculating the time difference, they will both be converted to a smaller unit (in seconds). You just need to subtract them to create the timedelta64 object:
In [6]: t1-t0 Out[6]: array([ 0, 60, 120, 180, 240], dtype='timedelta64[s]')
If you want a numerical response, do
In [7]: (t1-t0).astype('int') Out[7]: array([ 0, 60, 120, 180, 240])
Note that I never used a for structure to scan arrays. This will degrade efficiency by preventing vectorization.
bmello
source share