Categories
Python Answers

How to calculate time difference between two Python Pandas columns in hours and minutes?

Spread the love

Sometimes, we want to calculate time difference between two Python Pandas columns in hours and minutes.

In this article, we’ll look at how to calculate time difference between two Python Pandas columns in hours and minutes.

How to calculate time difference between two Python Pandas columns in hours and minutes?

To calculate time difference between two Python Pandas columns in hours and minutes, we can subtract the datetime objects directly.

For instance, we write:

import pandas

df = pandas.DataFrame(columns=['to', 'fr', 'ans'])
df.to = [
    pandas.Timestamp('2020-01-24 13:03:12.050000'),
    pandas.Timestamp('2020-01-27 11:57:18.240000'),
    pandas.Timestamp('2020-01-23 10:07:47.660000')
]
df.fr = [
    pandas.Timestamp('2020-01-26 23:41:21.870000'),
    pandas.Timestamp('2020-01-27 15:38:22.540000'),
    pandas.Timestamp('2020-01-23 18:50:41.420000')
]
df.ans = (df.fr - df.to).astype('timedelta64[h]')
print(df)

We create a Panda DataFrame with 3 columns.

Then we set the values of the to and fr columns to Pandas timestamps.

Next, we subtract the values from df.fr by df.toand convert the type totimedelta64withastypeand assign that todf.ans`.

Therefore, df is:

                       to                      fr   ans
0 2020-01-24 13:03:12.050 2020-01-26 23:41:21.870  58.0
1 2020-01-27 11:57:18.240 2020-01-27 15:38:22.540   3.0
2 2020-01-23 10:07:47.660 2020-01-23 18:50:41.420   8.0

according to what’s printed.

Conclusion

To calculate time difference between two Python Pandas columns in hours and minutes, we can subtract the datetime objects directly.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *