How to Check if the Current Time is in a Range in Python?

Problem Formulation

Given a timestamp x such as the current time and a time interval marked with start and end timestamps.

Goal: Create a function that checks whether the given timestamp falls in the interval [start, end], so that x>=start and x<=end.

Constraints: If the interval is empty when start >= end and x != start, the function should return False.

Method 1: Comparisons of datetime Objects

Datetime objects are comparable, so you can compare datetime objects using the <, >, <=, >=, and == comparison operators. Therefore, you can use the expression start <= current <= end to check if a current time falls into the interval [start, end] when assuming that start, end, and current are datetime objects.

To check if the current time falls in a specific interval, use the following steps (see code):

  1. Import the datetime module.
  2. Create a function time_in_range that takes three arguments—start, end, and current time— and returns whether the current time falls in the interval [start, end].
  3. If the interval is empty, it simply checks whether the current time is larger than the start time or smaller than the end time.
  4. Create the start and stop datetime objects using datetime.time() methods. To get the current time, use datetime.datetime.now().time().
  5. Call time_in_range(start, end, current) to check if the current time falls in the interval [start, end].

Here’s the code:

import datetime

def time_in_range(start, end, current):
    """Returns whether current is in the range [start, end]"""
    return start <= current <= end


start = datetime.time(0, 0, 0)
end = datetime.time(23, 55, 0)
current = datetime.datetime.now().time()

print(time_in_range(start, end, current))
# True (if you're not a night owl) ;)

The code returns True if you run it between (hh:mm:ss) 00:00:00 and 23:55:00 on your computer. Only if you run it between 23:55:00 and 23:59:59 it returns False.

Method 2: DateTimeRange

DateTimeRange is a Python library that allows you to check whether a time is within the time range using these three steps:

  1. Install the module with pip install DateTimeRange in your operating system shell or terminal.
  2. Create a time range object named time_range using the constructor DateTimeRange(start, stop).
  3. Use the keyword "in" to check whether a certain timestamp or even a smaller time range falls within the time range object such as current in time_range.

The documentation provides the following example code:

from datetimerange import DateTimeRange

time_range = DateTimeRange("2020-03-22T10:00:00+0900", "2025-03-22T10:10:00+0900")
print("2022-03-22T10:05:00+0900" in time_range)
print("2042-03-22T10:15:00+0900" in time_range)

time_range_smaller = DateTimeRange("2021-03-22T10:03:00+0900", "2022-03-22T10:07:00+0900")
print(time_range_smaller in time_range)

Here’s the output of this sample code:

True
False
True

The first timestamp falls within the range because the year 2022 is in [2020, 2025].

The second timestamp doesn’t fall into the range [2020, 2025] because it concerns year 2042 (probably the future when you’re reading this).

The third time interval is a smaller interval [2021, 2022] that is dominated by [2020, 2025]. Thus, it falls within the interval and the return value is True.

If you need the function to solve the problem formulation precisely, use the following code:

def time_in_range(start, end, current):
    """Returns whether current is in the range [start, end]"""
    return current in DateTimeRange(start, end)

print(time_in_range("2027-03-22T10:00:00+0900", "2025-03-22T10:10:00+0900", "2042-03-22T10:15:00+0900"))
# True

The code uses the string representations YYYY-MM-DDTHH:MM:SS+millisecs to specify the three timestamps start, end, and current.

Summary

Datetime objects are comparable, so you can compare datetime objects using the <, >, <=, >=, and == comparison operators.

Therefore, you can use the expression start <= current <= end to check if a current time falls into the interval [start, end] when assuming that start, end, and current are datetime objects.

Alternatively, you can use the Python library DateTimeRange to check whether a time is within the time range—but you need to install it first using pip install DateTimeRange.

Programmer Humor

Q: What is the object-oriented way to become wealthy?
πŸ’°

A: Inheritance.