Time difference in seconds from numpy.timedelta64

前端 未结 2 1807
春和景丽
春和景丽 2020-12-13 09:01

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         


        
相关标签:
2条回答
  • 2020-12-13 09:20

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

    seconds = dt / np.timedelta64(1, 's')
    
    0 讨论(0)
  • 2020-12-13 09:29

    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.

    0 讨论(0)
提交回复
热议问题