Sorting a list of objects by date [closed]

5

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

    
asked by anonymous 10.10.2016 / 18:43

1 answer

0

You can leave your class comparable to another one using 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 you 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 compared to another, we can use a sorted, sorted list, 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)
    
18.10.2016 / 00:49