Get File Metadata from S3 Using Python Boto

Get File Metadata from S3 Using Python Boto

I have some binary files in AWS S3, i need to get the file metadata like created time, modified time and accessed time using Python Boto API?

What we tried was copy the files to EC2 instance, from there we used os module stat method to get the times. I hope when we copy the files to EC2 instance these details are changed.

Sample code what i tried:

stat = os.stat(inputFile)
createdTime = datetime.fromtimestamp(stat[9]).strftime("%A, %B %d, %Y %I:%M:%S")

How to directly get these details from S3?

2 Answers

Boto3 has a function S3.Client.head_object:

The HEAD operation retrieves metadata from an object without returning the object itself. This operation is useful if you're only interested in an object's metadata.

Sample code to step through files in a bucket and request metadata:

#! /usr/bin/python3

import boto3
s3client = boto3.client('s3')

paginator = s3client.get_paginator('list_objects_v2')
page_iterator = paginator.paginate(Bucket='MyBucketName')
for bucket in page_iterator:
    for file in bucket['Contents']:
        print(file['Key'])
        try:
            metadata = s3client.head_object(Bucket='MyBucketName', Key=file['Key'])
            print(metadata)
        except:
            print("Failed {}".format(file['Key']))

use boto3 instead of boto. you can look at for anything about boto3's s3 apis. there are not many filters available, check if what you need is available there. Check this to start with

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.