Search code examples
pythonamazon-web-servicesamazon-s3boto3boto

find last modified date of a particular file in S3


According to this answer: https://stackoverflow.com/a/9688496/13067694

>>> import boto
>>> s3 = boto.connect_s3()
>>> bucket = s3.lookup('mybucket')
>>> for key in bucket:
       print key.name, key.size, key.last_modified
index.html 13738 2012-03-13T03:54:07.000Z
markdown.css 5991 2012-03-06T18:32:43.000Z
>>>

I can do something like this to find the last_modified dates. Here, they are using boto.connect_s3. But I was unable to import boto on AWS Lambda, it is probably no longer in use.

In my code snippet, I am already using boto3's s3_clientand s3_resource. I tried the last line to find the last modified date of a particular file in my bucket:

s3 = boto3.client('s3')
lst = s3.list_objects(Bucket='testunzipping')['Contents']

s3_resource = boto3.resource('s3')
bucket = s3_resource.Bucket('testunzipping')

s3.download_file('testunzipping','DataPump_10000838.zip','/tmp/DataPump_10000838.zip')
lastModified = bucket['DataPump_10000838.zip'].last_modified

but it gives me an error that "errorMessage": "'s3.Bucket' object is not subscriptable"

Is it possible to still find the last_modified date using boto3.client and resource alone? Plus, I am also downloading the file using s3.download_file. Can't I just extract the last_modified date while downloading it?


Solution

  • You can do it this way:

    import boto3
    
    s3 = boto3.resource("s3")
    s3_object = s3.Object("your_bucket", "your_object_key")
    print(s3_object.last_modified)