Python 与 numpy.timedelta64 的时差(以秒为单位)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14920903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:51:31  来源:igfitidea点击:

Time difference in seconds from numpy.timedelta64

pythondatetimenumpy

提问by sashkello

How to get time difference in seconds from numpy.timedelta64 variable?

如何从 numpy.timedelta64 变量中获得以秒为单位的时差?

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 dtto number (int or float) representing time difference in seconds.

我想转换dt为以秒为单位表示时差的数字(整数或浮点数)。

采纳答案by wim

You can access it through the "wrapped" datetime item:

您可以通过“包装的”日期时间项访问它:

>>> dt.item().total_seconds()
65.0

Explanation: here dtis an array scalarin numpy, which is a zero rank array or 0-dimensional array. So you will find the dthere 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.timedeltaobject.

说明:这里dt是一个数组标量in numpy,它是一个零秩数组或 0 维数组。所以你会发现dt这里也有 ndarray 拥有的所有方法,你可以做例如dt.astype('float'). 但它包装了一个 python 对象,在这种情况下是一个datetime.timedelta对象。

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.item(). 要索引数组标量,您可以使用使用空元组的 getitem 有点奇怪的语法:

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

这应该适用于所有版本的 numpy,但如果您使用的是 numpy v1.7+,最好直接使用较新的 numpy datetime API,如JF Sebastien此处的回答中所述。

回答by jfs

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

numpy.timedelta64()使用numpy1.7 实验性日期时间 API从对象获取秒数:

seconds = dt / np.timedelta64(1, 's')