Skip to content

Instantly share code, notes, and snippets.

@jzbruno
Created February 16, 2015 00:02
Show Gist options
  • Save jzbruno/948361e69190a4cd01a3 to your computer and use it in GitHub Desktop.
Save jzbruno/948361e69190a4cd01a3 to your computer and use it in GitHub Desktop.
Check if the current time is in between two times.
"""
Example of checking wether the current time is between
a start and end time. This assumes no access to timespan like functions
and is why the times are integers.
Use nose to run tests with `nosetests check_time_between.py`
"""
def test_before_window():
assert not is_in_window(1200, 1600, 1800)
def test_after_window():
assert not is_in_window(2000, 1600, 1800)
def test_during_window():
assert is_in_window(1700, 1600, 1800)
def test_during_window_crossover():
assert is_in_window(1700, 1600, 100)
def test_hour_combinations():
def check_is_in_window(start, end):
assert is_in_window(start + 30, start, end)
for start_hour in xrange(0, 23):
for end_hour in xrange(0, 23):
start = 0
if not start_hour == 0:
start *= 100
end = 0
if not end_hour == 0:
end *= 100
yield check_is_in_window, start, end
def is_in_window(now, start, end):
"""
Return true if now is between start and end.
Parameters should contain the current hour (24 hour clock) and minute as a
single integer. For example: 1:30 AM would be 130, 3:30 PM would be 1530.
"""
if start < end:
return start <= now and now <= end
else:
return not (end < now and now < start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment