Python 从时间增量获取总小时数?
如何获得时间增量中的总小时数 例如:Python 从时间增量获取总小时数?,python,pandas,Python,Pandas,如何获得时间增量中的总小时数 例如: >>> td = pd.Timedelta('1 days 2 hours') >>> td.get_total_hours() 26 注意:根据文档,.hours属性将返回小时组件: 只需找出1小时内可容纳多少个timedeltas即可: import numpy as np >> td / np.timedelta64(1, 'h') 26.0 试着说明为什么熊猫会在2小时内回来 import pan
>>> td = pd.Timedelta('1 days 2 hours')
>>> td.get_total_hours()
26
注意:根据文档,.hours
属性将返回小时组件:
只需找出1小时内可容纳多少个
timedelta
s即可:
import numpy as np
>> td / np.timedelta64(1, 'h')
26.0
试着说明为什么熊猫会在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
我得到的是以秒为单位的时间增量,再除以3600得到小时
round(td.total_seconds()/3600)
当我在jupyter笔记本中测试时,这种方法工作得更快
%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
我更喜欢pd.Timedelta(小时数=1),因为OP已经在使用pandas了。
%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