Syntax error Python program to find difference between current time and given time

Python program to find difference between current time and given time



When it is required to find the difference between the current time and a given time, a method can be defined, that takes the hours, minutes, and seconds as parameter. It then calculates the difference between two given times.

Below is a demonstration of the same −

Example

 Live Demo

def difference_time(h_1, m_1, h_2, m_2):

   t_1 = h_1 * 60 + m_1
   t_2 = h_2 * 60 + m_2

   if (t_1 == t_2):
      print("The times are the same")
      return
   else:
      diff = t_2-t_1

   hours = (int(diff / 60)) % 24

   mins = diff % 60

   print(hours, ":", mins)

if __name__ == "__main__":
   print("The difference between times are given below :")
   difference_time(13,20,11, 49)
   difference_time(17, 11, 9, 59)
   difference_time(21, 4, 11, 34)

Output

The difference between times are given below :
23 : 29
17 : 48
15 : 30

Explanation

  • A method named difference_time is defined that takes three parameters.

  • The times are converted into minutes.

  • When the timings are different, they are subtracted, and the hours and the minutes are displayed as output.

  • In the main method, this method is called by passing different parameter.

  • The output is displayed on the console.

Updated on: 2021-04-15T13:06:06+05:30

400 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements