0

i have an object, which has multiple values. one of its field is timestamp. While creating the object, i have converted the input string to timestamp.

DATETIME_FORMAT = '%d-%b-%y %H.%M.%S.%f %p'

class CustomObject:
    def __init__(self, input_data):
        entry_list = [entry.strip() for entry in input_data.split(',')]
        self.field_one = entry_list[0]
        self.field_two = entry_list[1]
        self.field_timestamp = datetime.strptime(entry_list[2], DATETIME_FORMAT)

There is list of CustomObject which I want to sort based on field_timestamp. How would i do that?

I was looking at sorted function but it takes in a lambda as an expression. In this case, i don't have an expression, i just have one field which i will be using to sort. how should it be done?

Em Ae
  • 8,167
  • 27
  • 95
  • 162
  • With a `lambda`. Convert to a `datetime` in the lambda – roganjosh Oct 25 '18 at 19:59
  • could you elaborate more? The datetime has already converted. – Em Ae Oct 25 '18 at 20:02
  • What do you mean "don't have an expression"? Use `sorted(..., key=lambda obj: obj.field_timestamp)` See https://docs.python.org/2/howto/sorting.html#key-functions – DeepSpace Oct 25 '18 at 20:02
  • How about using a SortedDict [http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html] object from sortedcontainers. If you use the timestamps as the key, then your list will be sorted. – Azim Oct 25 '18 at 20:02

1 Answers1

2
sorted_list = sorted(list_of_CustomObject, key=lambda x: x.field_timestamp)

but really you should use a member access method instead of the exposed member variable.

user3148225
  • 426
  • 1
  • 6
  • 17
  • 1
    "but really you should use a member access method instead of the exposed member variable" Why? Python is not Java or C – DeepSpace Oct 25 '18 at 20:04
  • it's not necessary but it's good form. If internal implementation changes later, there will be less to debug in the code that uses the object. – user3148225 Oct 25 '18 at 20:06
  • day by day i am falling in love with python. had it been in java, i would have to write 1-2 methods to do it properly. – Em Ae Oct 25 '18 at 20:16