How to calculate if a current day is inside or outside some recurrent event of duration of N hours?

53 Views Asked by At

Say, I have an event that starts at 1:30 and ends at 6:30 (for example, it could be any time). The event is recurrent that is it's repeating. In this example, it repeats every second day but it can be 2, 3 and any other number.

I need to figure out if the given datetime is inside of any such slots.

Say, the Nov, 16th 4:17 am is out, but Nov, 17th 4:17 is in.

Maybe, there are libraries for Python that can do it? Or there is some simple approach to calculate it?

Example of recurring events

Using dateutil.rrule, I probably can calculate dates but I can't figure out how to apply this knowledge to solve the task.

So it should be a function of this signature:

def inside_slot(start_datetime, end_datetime, interval, given_datetime):

   '''
   Returns True if the given_datetime inside of a recurring 
   slot, else False.
   '''
   pass
1

There are 1 best solutions below

0
On

You can use datetime to compare the given datetime with the start and end times of the event, and then check if it falls within any recurring slots.

Here's an example code using datetime:

from datetime import datetime, timedelta

def is_in_recurring_slot(event_start_time, event_end_time, recurring_interval, given_time):
    # Parse the given event start and end times as datetime objects
    event_start = datetime.strptime(event_start_time, '%I:%M %p')
    event_end = datetime.strptime(event_end_time, '%I:%M %p')

    # Parse the given time as a datetime object
    given_datetime = datetime.strptime(given_time, '%b %dth %I:%M %p')

    # Calculate the duration of the event
    event_duration = event_end - event_start

    # Check if the given time is within any recurring slots
    while event_start < given_datetime:
        if given_datetime <= event_end:
            return True

        # Increment the start and end times using the recurring interval
        event_start += timedelta(days=recurring_interval)
        event_end = event_start + event_duration

    # The given time is not within any recurring slots
    return False

# Example usage
event_start_time = '1:30 PM'
event_end_time = '6:30 PM'
recurring_interval = 2

given_time = 'Nov 16th 4:17 AM'
is_in_slot = is_in_recurring_slot(event_start_time, event_end_time, recurring_interval, given_time)
print(f"Given time {given_time} is in recurring slot: {is_in_slot}")

Keep in mind that you need to modify the format strings in the strptime method according to your specific date and time format. Additionally, you need to handle the case when the given time is before the first recurring slot.