Get total number of hours from a Pandas Timedelta?

PythonPython 3.xPandasDatetime

Python Problem Overview


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

For example:

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

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

>>> td.hours
2

Python Solutions


Solution 1 - Python

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

import numpy as np

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

Solution 2 - Python

Just try to show why pandas returns 2 hours.

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

Solution 3 - Python

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

round(td.total_seconds() / 3600) .

When I tested in jupyter notebook this approach works faster

%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

Solution 4 - Python

So much simpler to use Pandas' Timedelta components.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid WoleverView Question on Stackoverflow
Solution 1 - PythonAmi TavoryView Answer on Stackoverflow
Solution 2 - PythonJianxun LiView Answer on Stackoverflow
Solution 3 - Pythonhru_dView Answer on Stackoverflow
Solution 4 - PythonjeanhuguesroyView Answer on Stackoverflow