Python program to find difference between current time and given time
In this tutorial, we will calculate the difference between the current time and the given time. Our objective is to find the difference between the current time (h1:m1) and the specified time (h2:m2), where h1, h2, and m1,m2 are hours and minutes respectively.
Let us see the input-output of the program for better understanding:
In the above figure, we can see that the current time is 4:5 and the given time is 6:7 then the difference is converted into h:m format, and the answer is 2:2. In the second example, the time is 1:1 and the given time is 1:1 as both are the same it will print that the time is the same.
Approach
When determining the difference between the current time and a specified time, a method that accepts the hours, minutes, and seconds as parameters can be defined. The difference between the two timings is then calculated. The approach for solving this program is:
- First, we will have to convert the given times into minutes and found the difference in minutes.
- Then If the difference is there, we will have to convert the difference value into hours and minutes.
- After conversion return the value
- If no difference is found i.e., 0 then print both are same
Algorithm
As of now, we have a rough understanding of how we will calculate the difference between the current time and the given time. Let us now jump into the algorithm followed by the program for better understanding:
- define a function time_difference(h1, m1, h2, m2)
- convert h1:m1 into minutes
- convert h2:m2 into minutes
- Calculate basic difference
- Calculate hours from the difference
- Calculate minutes for the difference
- Print the difference
Python Program
As per the algorithm let us write the code to calculate the difference between the current time and the given time
def time_difference(h1, m1, h2, m2):
print("The current times: ", h1, ":", m1)
t1 = h1 * 60 + m1
print("The given times:", h2, ":", m2)
t2 = h2 * 60 + m2
if(t1 == t2):
print("The difference: Both are Same !")
return
else:
difference = t2 - t1
h = (int(difference/60)) % 24
m = difference % 60
print("The difference: ", h, ":", m, "\n")
time_difference(4, 5, 6, 7)
time_difference(1, 1, 1, 1)
The current times: 4: 5
The given times: 6: 7
The difference: 2: 2
The current times: 1: 1
The given times: 1: 1
The difference: Both are Same!
Conclusion
In this tutorial, we have performed the difference between the current time and given time with help of python. If there is a difference we print it in the format of an hour: minute and if there is no difference we print that Both are the same!.