In today’s tutorial we will learn how to use how to calculate time differences in Python and Pandas.
Find the difference between timestamps in seconds
We will start by defining our datetime time stamps. We then define a timedelta. The timedelta is by default expressed in days and hours. Therefore, we then use the total_seconds() method to calculate the difference in seconds.
import datetime #define the timestamps start_time = datetime.datetime(2022,8,19,15,30,0) end_time = datetime.datetime(2022,8,25,20,30,0) #define a timedelta object elapsed_time = end_time - start_time #calculate the difference in seconds time_seconds = (elapsed_time).total_seconds() print('The elapsed time is: ' + str(time_seconds) +' seconds')
The result will be:
The elapsed time is: 536400.0 seconds
Important: Before working with the datetime module, make sure that you have imported it into your Python program. Otherwise you will receive the following name error:
NameError: name 'datetime' is not defined
Calculate the time difference in minutes and hours
In a similar fashion we can perform additional tweaks to find the time in minutes.
time_minutes = (end_time - start_time).total_seconds()/60 print('The elapsed time is: ' + str(time_minutes) +' minutes')
This will return:
The elapsed time is: 8940.0 minutes
And for hours:
time_hours = (end_time - start_time).total_seconds()/3600 print('The elapsed time is: ' + str(time_hours) +' hours')
The elapsed time is: 149.0 hours
Calculate time differences with Pandas
In Pandas the time calculation work quite similarly. Below is a trivial example, typically your data will be organized in columns containing timestamps. Still, the mechanics are similar.
import pandas # creating timestamps start_time_pd = pd.to_datetime(start_time) end_time_pd = pd.to_datetime(end_time) #calculating the timedelta and returning the delta in seconds delta_pd = (end_time_pd-start_time_pd) time_seconds = delta_pd.total_seconds() print('The elapsed time is: ' + str(time_seconds) +' seconds')