Check if datetime is in hour range

I was wondering what is the best way to check whether a given datetime in Python falls in an hourly range, independetly from year, month or day. For example, let's say my range is between 3PM (15:00) and 5PM (17:00), this is my current solution:

from datetime import datetime

my_time = datetime.strptime('2022-01-16T15:59:13Z', '%Y-%m-%dT%H:%M:%SZ')
if my_time.hour < 15 or my_time.hour >= 17:
    print("NOT IN RANGE")
else:
    print("IN RANGE")

Is there any better solution? Thanks in advance.


Here's a way to do it with a dedicated function returning a boolean.

import datetime as dt


HOUR_MIN = 15
HOUR_MAX = 17

def check_time_in_range(input_dt):
    return HOUR_MIN <= input_dt.hour < HOUR_MAX

my_time = dt.datetime.strptime('2022-01-16T15:59:13Z', '%Y-%m-%dT%H:%M:%SZ')

print("In range" if check_time_in_range(my_time) else "Not in range")

you can do it like this if you prefer:

def time_in_range(start, end, x):
    """Return true if x is in the range [start, end]"""
    if start <= end:
        return start <= x <= end
    else:
        return start <= x or x <= end

time_in_range(15, 17, my_time.hour)