Ordering a list of objects by date

Asked

Viewed 1,174 times

5

I have a list of objects and each object in this list has an attribute that is a date, in the same string format. How do I sort this list of objects by that date?

  • 1

    Using date or string order? You know that the order will go wrong having this attribute as a string, right?

  • I need it to be sorted by date. It would be better if I used the python date object when filling in the attribute?

  • I don’t know, only you can know this. If you need her like Date most of the time, you should be using as Date, if needed as string always and only needs it to be Date When it comes to order, perhaps there is a better solution. Depending on the amount of data, it is even considerable to convert before ordering in the latter case. But everything is relative...

  • I think I got it wrong.

  • Got it, my situation is: I take this date information straight from a txt file and put it in another txt file only in a different layout. I have been asked to sort this information by date before I record it in the new layout. In this scenario, to do this ordering, it is better to use as Date or as String

1 answer

0

You can leave your class comparable to another by the date attribute.

    from functools import total_ordering
    from datetime import date

    @total_ordering
    class obj:
        def __init__(self, dia, mes, ano):
            self.data = date(ano, mes, dia)

        def __eq__(self, other):
            return self.data == other.data
        def __lt__(self, other):
            return self.data < other.data

Or can use direct by date, it directly accepts comparison.

    >>>data1 = date(2012, 12, 1)
    >>>data2 = date(1999, 10, 1)
    >>>data1 > data2

Since the object can now be comparable to another, we can use a Sorted, to sort a list, with n-objects, or any other sort algorithm. Ex:

   a = obj(1, 12, 1990)
   b = obj(1, 12, 1991)
   c = obj(1, 12, 1992)

   l = [b, a, c]

   r = sorted(l)

   print(r[1].data)
  • The answer is incomplete. With the given information it is still impossible to accomplish what the author needs. Specify what to do next. I mean, an example sorting algorithm or if there is a function to be used.

  • In my case the date is an attribute of an object, there is a list of that same object and I want to sort that list by the date attribute of the object. But your reply helped me to see that regardless of what is done, it is much better to use the same Data object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.