与numpy.timedelta64的时差(秒) [英] Time difference in seconds from numpy.timedelta64

查看:2645
本文介绍了与numpy.timedelta64的时差(秒)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从numpy.timedelta64变量获取时间差?

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

我想转换 dt to number(int or float),以秒为单位表示时间差。

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

推荐答案

它通过包裹日期时间项目:

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

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

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

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.

要获得原始标量,您可以使用 dt.item()。要索引数组标量,您可以使用一个空元组的getitem有点奇怪的语法:

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]')

这应该适用于所有版本的numpy,但是如果您使用numpy v1.7 +,则可以直接使用较新的numpy datetime API,如 JF Sebastien 这里。

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.

这篇关于与numpy.timedelta64的时差(秒)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆