Home > Backend Development > Python Tutorial > How to Calculate the Time Difference in Hours and Minutes Between Two Pandas Columns?

How to Calculate the Time Difference in Hours and Minutes Between Two Pandas Columns?

Susan Sarandon
Release: 2024-12-01 22:52:10
Original
858 people have browsed it

How to Calculate the Time Difference in Hours and Minutes Between Two Pandas Columns?

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)
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template