Search code examples
pythonstringheappriority-queuemax-heap

Python heapq Priority Queue Maxheap


I understand that priority queues using heapq are implemented as a minheap. I need to make a priority queue implemented as a maxheap that sorts elements by an AWS datetime string. I want elements with the most recent datetime to be popped off of the queue first when I call the heapq.heappop() method. Everything online seems to point towards just using the minheap but making your values negative during input so that greater values are pushed to the top instead of the bottom. However, I can't seem to find any way to actually apply this to a datetime string like this '2021-06-03T16:11:14.206650Z'. Is there a way that I can make that string 'negative' or somehow make it so that more recent dates are popped from the heap first?


Solution

  • There are several ways to approach this.

    One is to convert the date/time to an ordinal, and negate that

    -dateutil.parser.parse('2021-06-03T16:11:14.206650Z').toordinal()
    

    If you want to retain the original date string, then put this number in a tuple together with the date string.