Calculate Time Difference Between Time Strings

In this article, we are going to learn how to calculate the time difference or time gap between 2 given times. We will ask user to enter the time 1 and time 2 for which we want to calculate the time difference. Then we will substract time 1 from time 2 so we can get the time difference between the two times.

Environment & Requirements –

Python interpreter is required to run this program.

Program to Substract time strings

In this example, we are first calculating the time difference and then showing it in seconds, minutes and hours also. If we want time difference in seconds then no need to convert in minutes or hours.

from datetime import datetime

#FirstTime
first_time = datetime.strptime("3:00:00","%H:%M:%S")
print("First time string is : " , first_time.time())
#Second Time
second_time = datetime.strptime("5:15:21","%H:%M:%S")
print("Second time string is : " , second_time.time())

difference = second_time - first_time

second = difference.total_seconds()
print("The Time Difference in seconds is: " , second)

minutes  = second / 60
print("The Time Difference in minutes : " , minutes)

hours = second / (60*60)  
print("The Time Difference in hours : " , hours)

Output –
First time string is : 03:00:00
Second time string is : : 05:15:21
The Time Difference in seconds is: : 8121.0
The Time Difference in minutes : 135.35
The Time Difference in hours : 2.255333333333334

Program Code Explanation

• Use the from datetime import datetime statement to import a datetime class from a datetime module.
• The strptime function use to convert a time string into a datetime object as per this format(%H: %M: %S)are Hours, Minutes, Seconds.
• The difference variable store the subtract value of first_time and second_time.
• The difference.total_s65econds, use to get the time difference in seconds.
• Seconds divided by 60 to get the difference in minutes.
• Seconds divided by 60*60(3600) to get the difference in hours.