Get latest two files using python

I'm trying to extract two ami id's from below output that are latest by date and time. How do I do that with python ? expected result: ami-x1, ami-x9

for image in images:
    created_date = datetime.strptime(image.creation_date, "%Y-%m-%dT%H:%M:%S.000Z")
    print(image.id, created_date)

output:

ami-x1 2018-03-14 14:53:38
ami-x2 2018-03-13 14:34:34
ami-x3 2018-03-09 16:24:49
ami-x4 2018-03-12 14:32:44
ami-x5 2018-03-13 15:29:37
ami-x6 2018-03-07 15:38:03
ami-x7 2018-03-08 15:33:44
ami-x8 2018-03-06 23:20:24
ami-x9 2018-03-13 17:01:15
ami-x10 2018-03-05 15:43:09

I can also generate image.id filename which has epoch timestamp. Is it easier to extract latest two using filename epoch ?

test1-useast2-1521039086
test2-useast2-1520951547
test3-useast2-1520612589
test4-useast2-1520865070
test5-useast2-1520954877
test6-useast2-1520436979
test7-useast2-1520523129
test8-useast2-1520378310
test9-useast2-1520960373
test10-useast2-1520264490

please let me know if you have any inputs.

1 answer

  • answered 2018-03-14 19:33 Daniele Murer

    You could try to use the builtin function sorted() with the power of lambdas:

    first, second = sorted(
        images,
        key=lambda x: datetime.strptime(x.creation_date, "%Y-%m-%dT%H:%M:%S.000Z"),
        reverse=True
    )[:2]
    print(first.id, second.id) # get and print id values