Sometimes, we want to calculate time difference between two Pandas columns in hours and minutes with Python.
In this article, we’ll look at how to calculate time difference between two Pandas columns in hours and minutes with Python.
How to calculate time difference between two Pandas columns in hours and minutes with Python?
To calculate time difference between two Pandas columns in hours and minutes with Python, we can use the Timedelta
class.
For instance, we write
t1 = pd.to_datetime('1/1/2015 01:00')
t2 = pd.to_datetime('1/1/2015 03:30')
print(pd.Timedelta(t2 - t1).seconds / 3600.0)
to create 2 Pandas datetimes with t1
and t2
.
And then we subtract both datetimes and put the difference in the Timedelta
class.
And then we get the difference in seconds with the seconds
property.
We divide the seconds by 3600.0 to get the difference in hours.
Conclusion
To calculate time difference between two Pandas columns in hours and minutes with Python, we can use the Timedelta
class.