Python

# How to Calculate Time Difference in Python

Time difference, in the programming world, means the difference between two points of time and is usually measured in seconds and milliseconds. Calculating the time difference is essential in various contexts such as data analysis, performance analysis, task scheduling, and more.

Knowing the time difference between your code’s beginning and end helps you to evaluate its performance. It plays a vital role in performing time-related tasks. Moreover, in-game animations, user interface and game stats are common components that work using the time difference. If you want to know the approaches of calculating the time difference, this tutorial is for you. Here, we will explain the different examples to find the time difference in Python.

## How to Calculate Time Difference in Python

In Python the “import datetime” concept imports the datetime as a class. So, when you use the datetime in your code, it refers to the datetime class and not the whole datetime module. It keeps the compiler from confusion when accessing it as a class.

## Calculate the Time Difference in Seconds

This method lets you measure the time elapsed between the two points of time.

1. First, import the datetime class from a datetime module. Please read the following given note to know more.
2. Initialize two variables with the initial and final point of time. Enter the values as “HH:MM:SS” where HH, MM, and SS represent Hour, Minute, and Seconds, respectively.
3. Use the strptime() function to represent the input time values in a format. Besides, use the time() function to turn these values in seconds.
4. Finally, calculate the time difference using the arithmetic operator “-”.

Here is the simple program of it:

from datetime import datetime
initial_time = "16:10:20"
final_time = "23:20:20"

time1 = datetime.strptime(initial_time, "%H:%M:%S")
print('Initial time is :', time1.time())

time2 = datetime.strptime(final_time, "%H:%M:%S")
print('Final time is :', time2.time())

time_difference = time2 - time1
print("Time difference is", time_difference.total_seconds(), "seconds")

## Calculate the Time Difference in Hours, Minutes, and Seconds

In some cases, you might need to calculate time in different units:

1. Import datetime as a class.
2. Store the initial and final values of time in two variables. After that, use the strptime() function to correct their format.
3. Use the arithmetic operators and logic to determine the required units’ time difference.

You can use the following program for it:

from datetime import datetime
initial = "16:10:20"
final = "23:20:20"
time_1 = datetime.strptime(initial, "%H:%M:%S")
time_2 = datetime.strptime(final, "%H:%M:%S")
time_difference = time_2 - time_1
sec = time_difference.total_seconds()
print('The time difference is of' , sec, 'seconds')
min = sec / 60
print('The time difference is of' , min, 'minutes')
hour = sec / 3600
print('The time difference is of' , hour, 'hours')

You’ll get the following result upon running the previous piece of code:

## Calculate the Time Difference of the Execution of Your Program

Knowing the execution time of your program is an effortless process. This section explains it briefly.

Add two variables, one at the beginning and the other one at the end, to your code. Initialize them as datetime.now() to store the value of the current time.

Use the total_seconds() function to calculate the time difference. This is the time that your program takes for execution.

from datetime import datetime
start = datetime.now()
#........................
#........................
end = datetime.now()
difference = (end - start).total_seconds()
print('Your program took', difference, 'seconds to execute.')

You’ll get the following result upon compiling the previous program:

## Calculate the Time Difference with the Divmod() Function

The divmod() function in Python takes a pair of numbers as input and returns an array that comprises their quotient and remainder.

You can use the divmod() function to segregate the number of seconds into minutes and seconds. For example, 1520 seconds is converted to 252 minutes and 2 seconds.

Example 1: When you have date and time.

import datetime
initial_datetime = datetime.datetime(202, 9, 1, 8, 15, 21)
final_datetime = datetime.datetime(2023, 9, 1, 8, 15, 41)
time_difference = (final_datetime  - initial_datetime).total_seconds()
print('The time difference is ', time_difference, 'seconds')
difference_minutes = divmod(time_difference, 60)
print('Time Difference is ', difference_minutes[0], 'minutes', difference_minutes[1], 'seconds')

Example 2: Same date but different times.

from datetime import datetime
initial_time = "20:12:23"
final_time = "21:43:18"
time_1 = datetime.strptime(initial_time, "%H:%M:%S")
time_2 = datetime.strptime(final_time, "%H:%M:%S")
time_difference = (time_2 - time_1).total_seconds()
print('The time difference is', time_difference, 'seconds')
difference_minutes = divmod(time_difference, 60)
print('Time difference in minutes is', difference_minutes[0], 'minutes and', difference_minutes[1], 'seconds' )

## Conclusion

Understanding the time difference calculator in Python is essential for many tasks. That’s why we included various examples which will help you to understand the time difference concept in Python. Furthermore, we explained how to convert the obtained time difference value into various time units.