How to use the divmod( ) function In Python

We can get a more precise time difference using the divmod( ) function. Using this function get the difference in a number of days also.

Python3




import datetime
    
time1 = datetime.datetime(2018, 10, 12, 20, 15, 40)
time2 = datetime.datetime(2015, 2, 10, 15, 41, 30)
  
difference = time1 - time2 
print('Difference is : ', difference)
    
minutes = divmod(difference.total_seconds(), 60
print('Difference in minutes: ', minutes[0],
      'minutes', minutes[1], 'seconds')
    
  
minutes = divmod(difference.seconds, 60
print('Total difference in minutes: ', minutes[0], 'minutes',minutes[1], 'seconds')


Output:

Difference is :  1340 days, 4:34:10
Difference in minutes:  1929874.0 minutes 10.0 seconds
Total difference in minutes:  274 minutes 10 seconds

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

...