Search code examples
pythonpython-3.xpython-datetime

How can I see if at least N times in a list of times fall within a 24-hour time span?


I have a handful of different dates and times, represented as a handful of datetime objects in a list.

from datetime import datetime

arr = [datetime(2023, 9, 1, hour=4, minute=3),
       datetime(2023, 9, 1, hour=2, minute=15),
       datetime(2023, 9, 1, hour=6, minute=45),
       # trimmed for brevity
]

If I wanted to see if two datetime objects fell within 24-hours of each other, that isn't terribly hard to do. Except, I'm trying to see if, given a list of datetime objects, at least n of them can be contained within a 24-hour time span.

For a real-world use case of this, those timestamps might represent sign-ins on a user account, and if a user attempts to log in too n times in 15 minutes, I might choose to take some action based on that*.

How can this be done in Python?


*Don't worry, I'm not actually trying to DIY authentication - that is purely an example.


Solution

  • If I understand you correctly, you can sort the array and then use moving window of certain size. Then check if first and last element of this window falls to desired range:

    from datetime import datetime
    
    
    def check_arr(arr, seconds=60 * 60 * 24, window=3):
        if len(arr) < window:
            return False
    
        for i in range(len(arr) - window + 1):
            first, *_, last = arr[i : i + window]
            s = (last - first).total_seconds()
            if s <= seconds:
                return True
    
        return False
    
    
    arr = [
        datetime(2023, 9, 1, hour=4, minute=3),
        datetime(2023, 9, 1, hour=2, minute=15),
        datetime(2023, 9, 1, hour=6, minute=45),
        # trimmed for brevity
    ]
    
    print(check_arr(sorted(arr)))
    

    Prints:

    True