Python 从 Pandas Timedelta 获取总小时数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31283001/
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-19 09:45:23  来源:igfitidea点击:

Get total number of hours from a Pandas Timedelta?

pythonpandas

提问by David Wolever

How can I get the total number of hours in a Pandas timedelta?

如何获得 Pandas timedelta 中的总小时数?

For example:

例如:

>>> td = pd.Timedelta('1 days 2 hours')
>>> td.get_total_hours()
26

Note: as per the documentation, the .hoursattribute will return the hours component:

注意:根据文档,该.hours属性将返回小时组件

>>> td.hours
2

采纳答案by Ami Tavory

Just find out how many timedeltas of 1 hour fit into it:

只需找出timedelta1 小时中有多少s 适合它:

import numpy as np

>> td / np.timedelta64(1, 'h')
26.0

回答by Jianxun Li

Just try to show why pandas returns 2 hours.

试着说明为什么大熊猫返回 2 小时。

import pandas as pd

td = pd.Timedelta('1 days 2 hours')

td.components

Out[45]: Components(days=1, hours=2, minutes=0, seconds=0, milliseconds=0, microseconds=0, nanoseconds=0)

td / pd.Timedelta('1 hour')

Out[46]: 26.0

回答by Hrushikesh Dhumal

I am getting the time delta in seconds and dividing it by 3600 to get hours

我以秒为单位获得时间增量并将其除以 3600 以获得小时

round(td.total_seconds() / 3600).

round(td.total_seconds() / 3600).

When I tested in jupyter notebook this approach works faster

当我在 jupyter notebook 中测试时,这种方法运行得更快

%timeit td / np.timedelta64(1, 'h') 
The slowest run took 19.10 times longer than the fastest. This could mean that an intermediate result is being cached. 
100000 loops, best of 3: 4.58 μs per loop

%timeit round(td.total_seconds() / 3600)
The slowest run took 18.08 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 401 ns per loop