Created
September 28, 2020 09:54
-
-
Save davedavis/e84c96e94ea01172b81df4d8425ca0a5 to your computer and use it in GitHub Desktop.
Python - Check if current time is in a given range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime, time | |
def is_time_between(begin_time, end_time): | |
# If check time is not given, default to current UTC time | |
check_time = datetime.utcnow().time() | |
if begin_time < end_time: | |
return begin_time <= check_time <= end_time | |
else: # crosses midnight | |
return check_time >= begin_time or check_time <= end_time | |
print(datetime.utcnow().time()) | |
# Original test case from OP | |
print(is_time_between(time(10, 30), time(16, 30))) | |
# Test case when range crosses midnight | |
print(is_time_between(time(22, 0), time(4, 00))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment