0

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?

1
  • Don't use the string itself as the key; use a negative offset compute from the date time and a "maximum" time (like the time at which the program starts). Commented Jun 17, 2021 at 20:12

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.