LearnFrenzy
Sign in Take a free test

Operators and Expressions · Operators Coding Problems · Question 7

Time difference between two clock times in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Read start and end times in HH:MM (24-hour) form and print the duration in hours and minutes. If the end is earlier, the shift runs past midnight.

Solution
main.py Run
import sys

for line in sys.stdin.read().splitlines():
    start, end = line.split()
    sh, sm = map(int, start.split(":"))
    eh, em = map(int, end.split(":"))
    minutes = (eh * 60 + em - (sh * 60 + sm)) % (24 * 60)   # % wraps past midnight
    h, m = divmod(minutes, 60)
    print(f"{start} to {end}: {h} h {m:02d} min")

Output Verified by running it on Python 3

09:15 to 17:45: 8 h 30 min
22:30 to 06:10: 7 h 40 min
13:00 to 13:00: 0 h 00 min

Python's % never returns a negative number for a positive divisor, so a negative difference (an overnight shift) wraps to the right value.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links