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?
Tags are not the same thing as object metadata in S3. Metadata applies only to that object in S3 and cannot be searched on, as you can search with tags.
Show activity on this post. My recommendation is that you migrate from boto, which is essentially deprecated, to boto3 because boto3 supports signature v4 by default (with the exception of S3 pre-signed URLs which has to be explicitly configured).
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 https://boto3.readthedocs.io/en/latest/reference/services/s3.html 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 https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.list_objects_v2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With