如何使用boto3从s3获取最后修改的文件名

2024-05-04 04:22:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从amazons3的目录中获取最后修改过的文件。 我曾经试着只打印那个文件日期,但我得到了这个错误。在

TypeError: 'datetime.datetime' object is not iterable

import boto3
s3 = boto3.resource('s3',aws_access_key_id='demo', aws_secret_access_key='demo')

my_bucket = s3.Bucket('demo')

for file in my_bucket.objects.all():
    # print(file.key)
    print(max(file.last_modified))

Tags: 文件key目录awsdatetimes3bucketaccess
1条回答
网友
1楼 · 发布于 2024-05-04 04:22:16

这里有一个简单的片段。简而言之,你必须在所有文件中迭代查找最后修改的日期。然后您就有了具有此日期的打印文件(可能不止一个)。在

from datetime import datetime

import boto3

s3 = boto3.resource('s3',aws_access_key_id='demo', aws_secret_access_key='demo')

my_bucket = s3.Bucket('demo')

last_modified_date = datetime(1939, 9, 1).replace(tzinfo=None)
for file in my_bucket.objects.all():
    # print(file.key)
    file_date = file.last_modified.replace(tzinfo=None)
    if last_modified_date < file_date:
        last_modified_date = file_date

print(last_modified_date)

# you can have more than one file with this date, so you must iterate again
for file in my_bucket.objects.all():
    if file.last_modified.replace(tzinfo=None) == last_modified_date:
        print(file.key)
        print(last_modified_date)

相关问题 更多 >