Menu Close

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 subtract them directly after converting the values to timestamps.

For instance, we write

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

to create the df data frame with a few columns.

And then we assign timestamp values to the columns which we created with the Timestamp method.

And then we subtract the timestamps and convert them to the 'timedelta64[h]' type with astype.

Posted in Python, Python Answers