[英]how to get last modified filename using boto3 from s3
我想從 amazon s3 的目錄中獲取最后修改的文件。 我現在只嘗試打印那個文件日期,但我收到了這個錯誤。
TypeError:'datetime.datetime' 對象不可迭代
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))
那里有一個簡單的片段。 簡而言之,您必須遍歷文件以查找所有文件中的最后修改日期。 然后你有這個日期的打印文件(可能不止一個)。
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():
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)
您將使用 s3 中的 boto3 獲得最后修改的文件名和文件夾名稱
功能工具和 reduce 的參考 -鏈接
from functools import reduce
import boto3
# replace with your access key and secret key
#s3 = boto3.resource('s3', aws_access_key_id='demo', aws_secret_access_key='demo')
import boto3
s3_client = boto3.client('s3', aws_access_key_id='demo', aws_secret_access_key='demo')
response = s3_client.list_objects_v2(Bucket='bucket_name', Prefix='subfolder name')
#Replace with your bucket name and subfolder name
all = response['Contents']
latest = max(all, key=lambda x: x['LastModified'])
print(latest)
#print(latest.values())
list(reduce(lambda x, y: x + y, latest.items()))
a = list(reduce(lambda x, y: x + y, latest.items()))
print(a[1])
輸出
# if you have one sub folder, you will get output in this below format
subfolder/filename.format
# if you having more than one sub folders, you will get output in this below format
subfolder1/subfolder2/filename.format
您需要根據您的存儲桶名稱獲取最后修改的文件夾和文件名
然后參考以下更改
#instead of this code
response = s3_client.list_objects_v2(Bucket='bucket_name', Prefix='subfolder name')
#remove prefix and subfolder name
response = s3_client.list_objects_v2(Bucket='bucket_name')
#Replace with you bucket name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.