0

I've got a list of datetime objects (key) and number of events that occur at those times(value). We'll call this the time_list.

Let's assume that I also have the following variables (these are also datetime objects):

datetime1 = Jan 1, 2019, 6:30PM

datetime2 = Jan 1, 2019, 8:30PM

What's the most efficient way to determine if there are any entries in the list that are > datetime1 and < datetime2?

I've used a for loop to loop over the items and then break when I find a match, but I'm wondering if there is something more efficient.

Thanks!

Jason Howard
  • 1,464
  • 1
  • 14
  • 43
  • 3
    Which ways did you try (and found out that aren't as efficient as expected)? – CristiFati Feb 04 '19 at 00:18
  • 2
    A dictionary isn't good for this task. It's better to use a sorted list where you can do binary search. – Primusa Feb 04 '19 at 00:21
  • Interesting. I'll try that. – Jason Howard Feb 04 '19 at 00:23
  • You can use an ordered dict to get the first date by using a hash lookup and then search the next dates in linear fashion, until you get to the end. – geckos Feb 04 '19 at 00:36
  • Someone above just said a dictionary isn't good for this and I should use a list, which I've implemented, but I"m not sure how to most efficiently search it. At the moment, I'm looping through each item in the dict until I get a hit and then I'm breaking out of the for loop. – Jason Howard Feb 04 '19 at 00:51
  • Do you break the loop after a single hit? So you'll get only one element, not all the elements that satisfy the criteria. Or I misunderstood? – Valentino Feb 04 '19 at 01:52
  • Possible duplicate of [Check if datetime instance falls in between other two datetime objects](https://stackoverflow.com/questions/5672862/check-if-datetime-instance-falls-in-between-other-two-datetime-objects) – Chris Larson Feb 04 '19 at 01:53

0 Answers0