How to convert a timedelta to hours. We can follow the same logic to convert a timedelta to hours. Instead of dividing the total_seconds() by the number of seconds in a minute, or dividing the timedelta object by timedelta(minutes=1) , we do it for hour.
Represents a duration, the difference between two dates or times. Timedelta is the pandas equivalent of python's datetime. timedelta and is interchangeable with it in most cases.
Timedeltas are differences in times, expressed in difference units, e.g. days, hours, minutes, seconds. They can be both positive and negative. Timedelta is a subclass of datetime.
Just find out how many timedelta
s of 1 hour fit into it:
import numpy as np
>> td / np.timedelta64(1, 'h')
26.0
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With