In: Computer Science
Write a Python program that reads in two times, an earlier time and a later time, and prints the difference between the two times in minutes as well as in hours/minutes. The format of the time is HH:MMAM or H:MMAM or HH:MMPM or H:MMPM. Also the AM or PM may be in lower case. A sample run of the program is shown below:
$ python3 Time.py Enter Earlier Time: 9:36aM Enter Later Time: 6:22PM Number of minutes between 9:36aM and 6:22PM = 526 The time difference between 9:36aM and 6:22PM = 8 hours and 46 minutes.
The formatting of the output should be exactly as shown above. This program should be placed in a file called Time.py.
t1=input('Enter Earlier Time: ')
t2=input('Enter Later Time: ')
h1,m1=t1.split(':')
h2,m2=t2.split(':')
#these 2 variables will store both time as minutes starting from 00:00 am
earlierMinutes=0
laterMinutes=0
if m1[-2:].lower()=='am':
earlierMinutes+=int(h1)*60+int(m1[:2])
else:
if int(h1)!=12:
earlierMinutes+=int(h1)*60+int(m1[:2])+12*60
else:
earlierMinutes=12*60+int(m1[:2])
if m2[-2:].lower()=='am':
laterMinutes+=int(h2)*60+int(m2[:2])
else:
if int(h2)!=12:
laterMinutes+=int(h2)*60+int(m2[:2])+12*60
else:
laterMinutes=12*60+int(m2[:2])
difference=laterMinutes-earlierMinutes
if difference<0:
difference=1440+difference
hrs=difference//60
mins=difference%60
print()
print('Number of minutes between',t1,'and',t2,'=',difference)
print('The time difference between',t1,'and',t2,'=',hrs,'hours and',mins,'minutes.')
