Calculate the time difference in hours, minutes and seconds

For finding differences in hours, minutes and seconds we will perform the following actions:

  • We will import daytime from daytime module
  • We will have start and end time of event
  • Then calculate the difference between them
  • And finally calculate the difference in hours, minutes and seconds

Python3




from datetime import datetime
  
start = datetime.strptime("4:25:40", "%H:%M:%S")
end = datetime.strptime("11:40:10", "%H:%M:%S")
  
difference = end - start
  
seconds = difference.total_seconds()
print('difference in seconds is:', seconds)
  
minutes = seconds / 60
print('difference in minutes is:', minutes)
  
hours = seconds / (60 * 60)
print('difference in hours is:', hours)


 Output:

difference in seconds is: 26070.0
difference in minutes is: 434.5
difference in hours is: 7.241666666666666

Calculate Time Difference in Python

In this article, we will discuss how to find the gap between two times in Python.

If we want to know the difference at which some particular events has occurred then we should know the time gap between them.

Example:

Input: Start time is : 06:20:50, End time is : 11:56:18
Output: Time difference in seconds is 20128.0 seconds 
Explanation: The time difference between the two times is 20128 seconds.

We will discuss the following topics:

  • Calculate the time difference in hours, minutes and seconds
  • Calculate the time interval between two given times
  • Using the divmod( ) function

Similar Reads

Calculate the time difference in hours, minutes and seconds

For finding differences in hours, minutes and seconds we will perform the following actions:...

Calculate the time interval between two given times

...

Using the divmod( ) function

Now we will calculate the time difference in seconds between two given times....

Finding the execution time of a program

...