Calculate Time Difference Between Two Pandas Columns in Hours and Minutes
When working with time-based data in Pandas, it's often necessary to calculate the difference between two date or datetime columns. By default, this calculation returns a datetime.timedelta object that includes days, hours, minutes, and seconds. However, in certain scenarios, you may only want to display the hours and minutes.
To achieve this, we can leverage the as_type method provided by Pandas. Here's how:
import pandas as pd import numpy as np # Create a DataFrame with 'todate' and 'fromdate' columns data = {'todate': pd.to_datetime(['2014-01-24 13:03:12.050000', '2014-01-27 11:57:18.240000', '2014-01-23 10:07:47.660000']), 'fromdate': pd.to_datetime(['2014-01-26 23:41:21.870000', '2014-01-27 15:38:22.540000', '2014-01-23 18:50:41.420000'])} df = pd.DataFrame(data) # Calculate the difference between 'todate' and 'fromdate' df['diff'] = df['fromdate'] - df['todate'] # Convert the 'diff' column to hours and minutes df['diff'] = df['diff'].astype(np.timedelta64, copy=False)
By converting the diff column to a timedelta64 object with a precision of hours, we disregard the days component and retain only the hours and minutes.
Output:
todate fromdate diff 0 2014-01-24 13:03:12.050 2014-01-26 23:41:21.870 58 hours 0 minutes 1 2014-01-27 11:57:18.240 2014-01-27 15:38:22.540 3 hours 41 minutes 2 2014-01-23 10:07:47.660 2014-01-23 18:50:41.420 8 hours 42 minutes
The above is the detailed content of How to Calculate the Time Difference in Hours and Minutes Between Two Pandas Columns?. For more information, please follow other related articles on the PHP Chinese website!