Boto3 S3, sort bucket by last modified

前端 未结 7 1563
眼角桃花
眼角桃花 2020-12-09 09:29

I need to fetch a list of items from S3 using Boto3, but instead of returning default sort order (descending) I want it to return it via reverse order.

I know you ca

7条回答
  •  孤城傲影
    2020-12-09 10:08

    If there are not many objects in the bucket, you can use Python to sort it to your needs.

    Define a lambda to get the last modified time:

    get_last_modified = lambda obj: int(obj['LastModified'].strftime('%s'))
    

    Get all objects and sort them by last modified time.

    s3 = boto3.client('s3')
    objs = s3.list_objects_v2(Bucket='my_bucket')['Contents']
    [obj['Key'] for obj in sorted(objs, key=get_last_modified)]
    

    If you want to reverse the sort:

    [obj['Key'] for obj in sorted(objs, key=get_last_modified, reverse=True)]
    

提交回复
热议问题