Calculating the Difference Between Two Time Periods in Python
Python is widely used for data processing, automation, and analytics. Often, you'll need to compute the duration between two events—such as time stamps from logs, process start/end times, or scheduled activities.
Python’s datetime
module makes this task straightforward and highly readable.
In this sub-article, we’ll explore how to calculate the time difference between two periods in Python.
This implementation follows the logic introduced in our C language lead article, but adjusted for Python syntax and time handling.
Required Module
Python provides built-in time functionality via:
from datetime import datetime
No external installation is needed for this basic use case.
Python Program: Calculate the Difference Between Two Time Periods
# DIFFERENCE BETWEEN TWO TIME PERIODS in Python using datetime module
from datetime import datetime
# Step-1 Define the start and end time using datetime objects
start_time = datetime(2025, 6, 3, 8, 20, 45)
end_time = datetime(2025, 6, 11, 14, 5, 30)
# Step-2 Subtract the two to get a timedelta object
difference = end_time - start_time
# Step-3 Extract total seconds and convert to hours, minutes, seconds
total_seconds = int(difference.total_seconds())
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
# Step-4 Display the time difference
print(f"\nTIME DIFFERENCE: {hours} HOURS, {minutes} MINUTES, {seconds} SECONDS")
Output
TIME DIFFERENCE: 197 HOURS, 44 MINUTES, 45 SECONDS
Explanation
-
We used the
datetime
constructor to manually define start and end times. -
The subtraction yields a
timedelta
object, which contains the duration. -
From the total seconds in the timedelta, we derived hours, minutes, and seconds.
Python's readable syntax allows for fast implementation of time difference calculations in projects like:
-
Log analysis
-
Task automation
-
Event tracking
Practical Metric: Total Time in Minutes
You can easily extend the program to show the total time in minutes, which is useful for billing, scheduling, or analytics.
total_minutes = total_seconds // 60
print("TOTAL TIME IN MINUTES:", total_minutes)
Output
TOTAL TIME IN MINUTES: 11864