Time difference in seconds from numpy.timedelta64

Question:

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(time1) - np.datetime64(time2)
print dt

0:01:05

I’d like to convert dt to number (int or float) representing time difference in seconds.

Asked By: sashkello

||

Answers:

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.

Answered By: wim

To get number of seconds from numpy.timedelta64() object using numpy 1.7 experimental datetime API:

seconds = dt / np.timedelta64(1, 's')
Answered By: jfs

You can simply cast the value to the desired time unit using np.astype, as shown in the example:

timedelta = np.datetime64('2011-07-18')-np.datetime64('2011-07-16')
seconds = timedelta.astype('timedelta64[s]').astype(np.int32)
hours = timedelta.astype('timedelta64[h]').astype(np.int32)
Answered By: Dema
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.