Python’s time difference calculation is essential for applications that work with time-stamped data or measure the duration of events. The time difference is also calculated when the user wants to measure the execution time of the program.

The datetime module and time module provide various functions to calculate the difference between specified times.

All these methods are explained in this guide:

## Using timedelta.total_seconds() Method

In Python, the “timedelta.total_seconds()” function is a method of the “timedelta” class in the datetime module. It retrieves the total number of seconds covered by a timedelta object. The following examples are used to calculate the time difference in seconds, milliseconds, hours, and minutes.

## Example 1: Calculate Time Difference in Seconds

The following code is used to calculate the time difference in seconds:

Code:

```import datetime
start_time = datetime.datetime.strptime("5:30:57", "%H:%M:%S")
print('Start time:', start_time.time())
end_time = datetime.datetime.strptime("10:50:38", "%H:%M:%S")
print('End time:', end_time.time())
delta = end_time - start_time
print(f"Time difference is {delta.total_seconds()} seconds")
```
• The “datetime” module is imported.
• The “striptime()” function is used to create a start and end datetime object based on the given format.
• The “time.time()” method is used to get the time component of the given datetime object.
• The end time and start time difference are calculated using the subtraction operator (-).
• The “total_seconds()” method of timedelta is utilized to retrieve the total number of seconds of the time difference.

Output:

The time difference has been calculated successfully.

## Example 2: Calculate Time Difference in Milliseconds

The below code is used to calculate the time difference in milliseconds:

Code:

```import datetime
start_time = datetime.datetime.strptime("5:30:57", "%H:%M:%S")
print('Start time:', start_time.time())
end_time = datetime.datetime.strptime("10:50:38", "%H:%M:%S")
print('End time:', end_time.time())
delta = end_time - start_time
mili_seconds = delta.total_seconds() * 1000
print(f"Time difference is {mili_seconds} milliseconds")
```

The “total_seconds()” method of the “timedelta” class in the datetime module returns a value that is multiplied by the integer “1000” to get the time difference in milliseconds.

Output:

The time difference has been calculated in milliseconds.

## Example 3: Calculate Time Difference in Hours and Minutes

The below code is used to calculate the time difference in hours and minutes:

Code:

```import datetime
start_time = datetime.datetime.strptime("5:30:57", "%H:%M:%S")
print('Start time:', start_time.time())
end_time = datetime.datetime.strptime("10:50:38", "%H:%M:%S")
print('End time:', end_time.time())
delta = end_time - start_time
seconds = delta.total_seconds()
minutes = seconds / 60
hours = seconds / (60 * 60)
print(f"\nTime difference is {seconds} seconds")
print(f"\nTime difference is {minutes} minutes")
print(f"\nTime difference is {hours} hours")
```
• The “total_seconds()” method is used to calculate the time difference in seconds.
• The return value of the “total_seconds()” method is divided by “60” to get the time difference in minutes.
• The return value of the “total_seconds()” method is divided by the expression “(60*60)” to get the time difference in hours.

Output:

The input time difference has been calculated in seconds, minutes, and hours.

## Example 4: Calculate the Time Difference Between Two timestamps

Timestamps are numerical representations of dates and times. Timestamps in Python retrieve the amount of time that has passed from the 1 January 1970 epoch time, which is set to 00:00:00 UTC.

Code:

```import datetime
start_time = datetime.datetime.fromtimestamp( 1652426243.907874)
print('Datetime Start:', start_time)
end_time = datetime.datetime.fromtimestamp(1652436243.907874)
print('\nDatetime End:', end_time)
delta = end_time - start_time
print('\nDifference in %H:%M:%S Format:', delta)
print('\nDifference in Seconds:', delta.total_seconds())
```
• The module named “datetime” is imported.
• The “datetime.datetime.fromtimestamp()” is used to create a datetime object for starting and ending time using the input timestamp value.
• The “fromtimestamp()” function takes the timestamp value and converts it into local time based on the system timezone.
• The difference between end time and start time is calculated and stored in the variable named “delta”.
• The time difference is printed on the screen in the standard “H:%M:%S” Format.
• The “total_seconds()” method returns the time difference in seconds.

Output:

The difference between the two timestamps has been calculated.

### Using time Module

The time module is used to deal with time-related tasks in Python. The below code uses the time module to calculate the time difference:

Code:

```import time
start_time = time.time()
time.sleep(5)
end_time = time.time()
print(end_time - start_time)
```
• The module named “time” is imported.
• The “time.time()” function is used to get the start and stop time.
• The end time is subtracted from the start time to calculate the difference between times.

Output:

The time difference has been calculated successfully.

Note: The “divmod()” function is also used to compute the time difference. It will retrieve a tuple containing the quotient and the remainder when one number is divided by another.

## Conclusion

To calculate the time difference in seconds, milliseconds, hours, and minutes the “datetime” module and “time” module are used in Python. The “timedelta.total_seconds()” function of the “timedelta” class in the datetime module is used to get the time difference in seconds. We can calculate the time difference in milliseconds, minutes, and other formats by performing basic mathematical expressions. This guide presented various ways to compute the time difference using Python.