the_lost_intern
the_lost_intern

Reputation: 37

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?

Upvotes: 0

Views: 676

Answers (2)

chepner
chepner

Reputation: 531075

Convert your timestamps to offsets from a maximum timestamp. Then the most recent timestamps will have the smallest keys, making a minheap appropriate.

Note that dateutil is a third-party module.

>>> import datetime, dateutil
>>> now = datetime.datetime.now().timestamp()
>>> june3 = dateutil.parser.isoparse('2021-06-03T16:11:14.206650Z').timestamp()
>>> june1 = dateutil.parser.isoparse('2021-06-01T00:00:00Z').timestamp()
>>> now - june3 < now - june1
True

Upvotes: 0

trincot
trincot

Reputation: 350212

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.

Upvotes: 3

Related Questions