Skip to content
Advertisement

Most efficient way to check if timestamp in list exists between two other timestamps?

I am trying to search a list of datetimes to check if there is a timestamp C that exists between timestamp A and B. I found the bisect stdlib but am not sure how to apply it here with datetime types.

My setup is similar to this:

JavaScript

I want to check if a timestamp in the list exists between my two variable times. I am doing this multiple times in a loop. The only solution I can come up with is another loop within it that checks the whole list. I would rather not do that for efficiency purposes as it is a lot of data. Any tips?

Advertisement

Answer

If you just want to check if a timestamp exists between start_time and end_time, and the list is sorted, then you just need to check the timestamp immediately following start_time (assuming it occurs in the list). If that is less than end_time, then the result is true. It would add a few checks to the code but would cut runtime in half by removing the need for bisect_right. The code would appear as follows:

JavaScript

Here left_index != len(insulin_timestamps) checks that start_time is not than any element in the list: if it is, then the result is False.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement