Boto3 S3, sort bucket by last modified
Slight improvement of above:
import boto3
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('myBucket')
files = my_bucket.objects.filter()
files = [obj.key for obj in sorted(files, key=lambda x: x.last_modified,
reverse=True)]
I did a small variation of what @helloV posted below. its not 100% optimum, but it gets the job done with the limitations boto3 has as of this time.
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('myBucket')
unsorted = []
for file in my_bucket.objects.filter():
unsorted.append(file)
files = [obj.key for obj in sorted(unsorted, key=get_last_modified,
reverse=True)][0:9]
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)]