How to get time difference in seconds from numpy.timedelta64 variable?
time1 = \'2012-10-05 04:45:18\'
time2 = \'2012-10-05 04:44:13\'
dt = np.datetime64(tim
To get number of seconds from numpy.timedelta64()
object using numpy 1.7 experimental datetime API:
seconds = dt / np.timedelta64(1, 's')
You can access it through the "wrapped" datetime item:
>>> dt.item().total_seconds()
65.0
Explanation: here dt
is an array scalar in numpy
, which is a zero rank array or 0-dimensional array. So you will find the dt
here also has all the methods an ndarray possesses, and you can do for example dt.astype('float')
. But it wraps a python object, in this case a datetime.timedelta
object.
To get the original scalar you can use dt.item()
. To index the array scalar you can use the somewhat bizarre syntax of getitem using an empty tuple:
>>> dt[()]
array(datetime.timedelta(0, 65), dtype='timedelta64[s]')
This should work in all versions of numpy, but if you are using numpy v1.7+ it may be better to use the newer numpy datetime API directly as explained in the answer from J.F. Sebastien here.