How to check a time is between two times in python

Question:

For example if I have

test_case1: (9:00 – 16:00) and

test_case2: (21:30 – 4:30)

that is, it works whether the first or second number is bigger than the other.

Asked By: Mat.S

||

Answers:

You can create datetime.datetime objects and compare

>>> start = datetime.datetime(2017, 7, 23, 9, 0)
>>> end = datetime.datetime(2017, 7, 23, 16, 0) 
>>> start < datetime.datetime(2017, 7, 23, 11, 0) < end
True
>>> start < datetime.datetime(2017, 7, 23, 18, 0) < end
False

If all times are on the same day, you could simply create datetime.times

>>> start = datetime.time(9, 0)
>>> end = datetime.time(16, 0) 
>>> start < datetime.time(11, 0) < end
True
>>> start < datetime.time(18, 0) < end
False
Answered By: Jonas Adler

You could simply convert the ‘times’ to minutes per day:

def minutesPerDay(tme):
    hours, minutes = tme.split(':')
    return (hours*60)+minutes

def checkTime(tme, tmeRange):
    return minutesPerDay(tmeRange[0]) < minutesPerDay(tme) < tmeRange[1]


print(checkTime('11:00', ('09:00', '16:00')))  # True
print(checkTime('17:00', ('09:00', '16:00')))  # False
Answered By: Maurice Meyer

You can use pure lexicographical string comparison if you zero-fill your times – then all you need is to determine if the second time is ‘smaller’ than the first time and for that special case check both days, e.g.:

def is_between(time, time_range):
    if time_range[1] < time_range[0]:
        return time >= time_range[0] or time <= time_range[1]
    return time_range[0] <= time <= time_range[1]

print(is_between("11:00", ("09:00", "16:00")))  # True
print(is_between("17:00", ("09:00", "16:00")))  # False
print(is_between("01:15", ("21:30", "04:30")))  # True

This will also work with time tuples (e.g. (9, 0)) instead of strings if that’s how you represent your time. It will even work with most time objects.

Answered By: zwer

Simple code

If start <= time <=end:
   return True
Answered By: Shaiful Islam
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.