从Pandas Timedelta获取总小时数?

Dav*_*ver 28 python pandas

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

例如:

>>> td = pd.Timedelta('1 days 2 hours')
>>> td.get_total_hours()
26
Run Code Online (Sandbox Code Playgroud)

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

>>> td.hours
2
Run Code Online (Sandbox Code Playgroud)

Ami*_*ory 41

只需找出timedelta适合它的1小时的s:

import numpy as np

>> td / np.timedelta64(1, 'h')
26.0
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢`pd.Timedelta(hours = 1)`因为OP已经在使用pandas了. (17认同)
  • 想知道为什么没有 Timedelta.hours 属性。 (2认同)

Jia*_* Li 21

试着说明为什么熊猫会回来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
Run Code Online (Sandbox Code Playgroud)


Hru*_*mal 7

我以秒为单位获取时间增量,然后将其除以3600得到小时

round(td.total_seconds() / 3600)

当我在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
Run Code Online (Sandbox Code Playgroud)