Mat.S
Mat.S

Reputation: 1854

How to check a time is between two times in python

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.

Upvotes: 5

Views: 20631

Answers (3)

zwer
zwer

Reputation: 25829

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.

Upvotes: 17

Maurice Meyer
Maurice Meyer

Reputation: 18136

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

Upvotes: 2

Jonas Adler
Jonas Adler

Reputation: 10809

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

Upvotes: 4

Related Questions