Skip to content

Calculating Simple Time Difference in Python

The challenge

In this challenge, you will be given a series of times at which an alarm goes off. Your task will be to determine the maximum time interval between alarms. Each alarm starts ringing at the beginning of the corresponding minute and rings for exactly one minute. The times in the array are not in chronological order. Ignore duplicate times, if any.


# If the alarm goes off now, it will not go off for another 23 hours and 59 minutes. solve(["14:51"]) = "23:59" # The max interval that the alarm will not go off is 11 hours and 40 minutes. solve(["23:00","04:22","18:05","06:24"]) == "11:40"
Code language: Python (python)

In the second example, the alarm goes off 4 times in a day.

The solution in Python code

Option 1:

from datetime import datetime def solve(arr): dts = [datetime(2000, 1, 1, *map(int, x.split(':'))) for x in sorted(arr)] delta = max(int((b - a).total_seconds() - 60) for a, b in zip(dts, dts[1:] + [dts[].replace(day=2)])) return '{:02}:{:02}'.format(*divmod(delta//60, 60))
Code language: Python (python)

Option 2:

def solve(arr): arr = sorted(int(m[:2]) * 60 + int(m[3:]) for m in set(arr)) arr += [arr[] + 1440] h, m = divmod(max(arr[i + 1] - arr[i] - 1 for i in range(len(arr) - 1)), 60) return "{:02}:{:02}".format(h, m)
Code language: Python (python)

Option 3:

def minutes(s): return int(s[:2]) * 60 + int(s[-2:]) def timeformat(m): return "{:02d}:{:02d}".format(m // 60, m % 60) def solve(arr): arr = list(set(arr)) m = [minutes(arr) for arr in sorted(arr)] difference = [(m[(i+1)%len(m)] - a - 1) % (60*24) for i, a in enumerate(m)] return(timeformat(max(difference)))
Code language: Python (python)

Test cases to validate our solution"Basic tests") test.assert_equals(solve(["14:51"]), "23:59") test.assert_equals(solve(["23:00","04:22","18:05","06:24"]),"11:40") test.assert_equals(solve(["21:14", "15:34", "14:51", "06:25", "15:30"]),"09:10")
Code language: Python (python)

See also  How to Split a String with Python
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x