Amazon S3
list bucket contents
modified date
AWS
cloud storage

aws s3 ls sort by date: list S3 bucket contents by last modified

Codemia Knowledge Hub ·

The S3 API cannot sort objects by modification date, so you retrieve the listing and sort it client-side. With the AWS CLI, pipe the output through sort (add -r for newest first). With Python and Boto3, sort the results in memory. For buckets with millions of objects, use S3 Inventory reports instead of repeated API calls, which are slow and costly at that scale.

Why S3 returns keys, not dates, in order

Every S3 object has a LastModified timestamp recording when it was created or last overwritten. It is returned by both ListObjectsV2 and HeadObject, as a UTC timestamp.

S3 does not keep a modification-date index. ListObjectsV2 returns objects in lexicographic key order (the object's path), so any date sorting happens after retrieval.

Sorting with the AWS CLI

List with dates

bash
1aws s3api list-objects-v2 \
2  --bucket my-bucket \
3  --query "Contents[].[LastModified,Size,Key]" \
4  --output text

This prints three columns: modification date, size in bytes and key.

Sort by modification date

bash
1aws s3api list-objects-v2 \
2  --bucket my-bucket \
3  --query "Contents[].[LastModified,Size,Key]" \
4  --output text | sort -k1

sort -k1 sorts by the first column (LastModified). S3 timestamps are ISO 8601, so lexicographic order is chronological order.

Newest objects first

bash
1aws s3api list-objects-v2 \
2  --bucket my-bucket \
3  --query "Contents[].[LastModified,Size,Key]" \
4  --output text | sort -k1 -r | head -20

-r reverses the order so the newest objects come first.

Filter by prefix

bash
1aws s3api list-objects-v2 \
2  --bucket my-bucket \
3  --prefix "logs/2026/" \
4  --query "Contents[].[LastModified,Key]" \
5  --output text | sort -k1 -r

A prefix reduces the objects returned, which speeds up both the API call and the sort.

aws s3 ls (simpler, less flexible)

bash
aws s3 ls s3://my-bucket/ --recursive | sort -k1,2

aws s3 ls prints date and time in the first two columns, so sorting on both (-k1,2) gives chronological order. It does not support JMESPath queries for filtering.

Sorting with Python and Boto3

Basic script

python
1import boto3
2
3s3 = boto3.client("s3")
4bucket_name = "my-bucket"
5
6response = s3.list_objects_v2(Bucket=bucket_name)
7
8if "Contents" in response:
9    objects = sorted(response["Contents"], key=lambda obj: obj["LastModified"])
10    for obj in objects:
11        print(f"{obj['LastModified']}  {obj['Size']:>10}  {obj['Key']}")

Paginating large buckets

list_objects_v2 returns at most 1,000 objects per call. Use the paginator for anything larger:

python
1import boto3
2
3s3 = boto3.client("s3")
4bucket_name = "my-bucket"
5paginator = s3.get_paginator("list_objects_v2")
6
7all_objects = []
8for page in paginator.paginate(Bucket=bucket_name):
9    if "Contents" in page:
10        all_objects.extend(page["Contents"])
11
12# Sort by LastModified descending (newest first)
13all_objects.sort(key=lambda obj: obj["LastModified"], reverse=True)
14
15for obj in all_objects[:50]:
16    print(f"{obj['LastModified']}  {obj['Size']:>10}  {obj['Key']}")

Filter by prefix and date range

python
1import boto3
2from datetime import datetime, timezone
3
4s3 = boto3.client("s3")
5bucket_name = "my-bucket"
6paginator = s3.get_paginator("list_objects_v2")
7
8cutoff = datetime(2026, 1, 1, tzinfo=timezone.utc)
9
10matching = []
11for page in paginator.paginate(Bucket=bucket_name, Prefix="uploads/"):
12    for obj in page.get("Contents", []):
13        if obj["LastModified"] >= cutoff:
14            matching.append(obj)
15
16matching.sort(key=lambda obj: obj["LastModified"], reverse=True)
17
18for obj in matching:
19    print(f"{obj['LastModified']}  {obj['Key']}")

The N most recently modified objects

python
1import boto3
2import heapq
3
4s3 = boto3.client("s3")
5bucket_name = "my-bucket"
6paginator = s3.get_paginator("list_objects_v2")
7
8# Use a heap to track the top 10 without sorting everything
9top_n = 10
10heap = []
11
12for page in paginator.paginate(Bucket=bucket_name):
13    for obj in page.get("Contents", []):
14        item = (obj["LastModified"], obj["Key"], obj["Size"])
15        if len(heap) < top_n:
16            heapq.heappush(heap, item)
17        else:
18            heapq.heappushpop(heap, item)
19
20# Sort the top N in descending order
21results = sorted(heap, reverse=True)
22for modified, key, size in results:
23    print(f"{modified}  {size:>10}  {key}")

The heap keeps memory proportional to the top N results instead of O(total_objects) for sorting the whole listing.

S3 Inventory for very large buckets

For millions of objects, repeated list_objects_v2 calls are slow and expensive. S3 Inventory produces a daily or weekly manifest of all objects as CSV, ORC or Parquet files in a destination bucket.

Configure S3 Inventory

bash
1aws s3api put-bucket-inventory-configuration \
2  --bucket my-bucket \
3  --id daily-inventory \
4  --inventory-configuration '{
5    "Id": "daily-inventory",
6    "IsEnabled": true,
7    "Destination": {
8      "S3BucketDestination": {
9        "Bucket": "arn:aws:s3:::my-inventory-bucket",
10        "Format": "CSV",
11        "Prefix": "inventory"
12      }
13    },
14    "Schedule": {
15      "Frequency": "Daily"
16    },
17    "IncludedObjectVersions": "Current",
18    "OptionalFields": ["LastModifiedDate", "Size", "StorageClass"]
19  }'

Query the inventory with Athena

Once delivered, query the inventory with Amazon Athena:

sql
1SELECT key, last_modified_date, size
2FROM s3_inventory.my_bucket_inventory
3WHERE last_modified_date > TIMESTAMP '2026-01-01 00:00:00'
4ORDER BY last_modified_date DESC
5LIMIT 100;

For buckets with tens of millions of objects, this is dramatically faster and cheaper than paginating the list API.

Which method to use

MethodBest ForMax ObjectsCostSort Support
AWS CLI + sortQuick checks, small bucketsUp to 100KStandard API pricingClient-side
Boto3 paginatorAutomation, scripting, filteringUp to 1M+Standard API pricingClient-side
Boto3 + heapqFinding top N in large bucketsAny sizeStandard API pricingHeap-based (efficient)
S3 Inventory + AthenaMillions of objectsUnlimitedInventory + Athena pricingSQL ORDER BY

IAM permissions required

json
1{
2  "Version": "2012-10-17",
3  "Statement": [
4    {
5      "Effect": "Allow",
6      "Action": [
7        "s3:ListBucket",
8        "s3:GetBucketLocation"
9      ],
10      "Resource": "arn:aws:s3:::my-bucket"
11    },
12    {
13      "Effect": "Allow",
14      "Action": "s3:GetObject",
15      "Resource": "arn:aws:s3:::my-bucket/*"
16    }
17  ]
18}

list_objects_v2 needs s3:ListBucket, a bucket-level permission applied to the bucket ARN without /*, not an object-level one.

Mistakes that give wrong or partial results

  • Expecting date order from the API. Objects always come back in lexicographic key order.
  • Skipping pagination. Without it you only see the first 1,000 objects (by key), which may not include the ones you want.
  • Sorting millions of objects in memory. It is slow and expensive; use S3 Inventory with Athena.
  • Reading LastModified as the completion time for multipart uploads. For multipart uploads, S3 sets it to when the upload was initiated, not when it completed.
  • Granting s3:GetObject instead of s3:ListBucket. Listing requires s3:ListBucket on the bucket resource.
  • Ignoring API costs. Each list_objects_v2 call is a LIST request. At $0.005 per 1,000 requests, a full scan of a 10 million object bucket takes 10,000 requests and costs about $0.05. The bigger cost is time, so S3 Inventory is still the better fit for repeated analysis.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design