简体   繁体   English

如何使用 Boto3 按上次修改日期过滤 s3 对象

[英]How to filter s3 objects by last modified date with Boto3

Is there a way to filter s3 objects by last modified date in boto3?有没有办法按 boto3 中的最后修改日期过滤 s3 对象? I've constructed a large text file list of all the contents in a bucket.我已经构建了一个包含存储桶中所有内容的大型文本文件列表。 Some time has passed and I'd like to list only objects that were added after the last time I looped through the entire bucket.一段时间过去了,我只想列出上次循环遍历整个存储桶后添加的对象。

I know I can use the Marker property to start from a certain object name,so I could give it the last object I processed in the text file but that does not guarantee a new object wasn't added before that object name.我知道我可以使用Marker属性从某个对象名称开始,所以我可以给它我在文本文件中处理的最后一个对象,但这并不能保证在该对象名称之前没有添加新对象。 eg if the last file in the text file was oak.txt and a new file called apple.txt was added, it would not pick that up.例如,如果文本文件中的最后一个文件是 Oak.txt 并且添加了一个名为 apple.txt 的新文件,则它不会选择该文件。

s3_resource = boto3.resource('s3')
client = boto3.client('s3')

def list_rasters(bucket):

    bucket = s3_resource.Bucket(bucket)

    for bucket_obj in bucket.objects.filter(Prefix="testing_folder/"):
        print bucket_obj.key
        print bucket_obj.last_modified

The following code snippet gets all objects under specific folder and check if the file last modified is created after the time you specify :以下代码片段获取特定文件夹下的所有对象,并检查最后修改的文件是否在您指定的时间之后创建:

Replace YEAR,MONTH, DAY with your values.用您的值替换YEAR,MONTH, DAY

import boto3
import datetime
#bucket Name
bucket_name = 'BUCKET NAME'
#folder Name
folder_name = 'FOLDER NAME'
#bucket Resource
s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket_name)    
def lambda_handler(event, context):
     for file in bucket.objects.filter(Prefix= folder_name):
         #compare dates 
         if file.last_modified.replace(tzinfo = None) > datetime.datetime(YEAR,MONTH, DAY,tzinfo = None):
             #print results
             print('File Name: %s ---- Date: %s' % (file.key,file.last_modified))

The code snippet below will use the s3 Object class get() action to only return those that meet a IfModifiedSince datetime argument.下面的代码片段将使用 s3 Object 类 get() 操作仅返回满足 IfModifiedSince 日期时间参数的那些。 The script prints the files, which was the original questions, but also saves the files locally.该脚本打印文件,这是原始问题,但也将文件保存在本地。

import boto3
import io
from datetime import date, datetime, timedelta


# Defining AWS S3 resources
s3 = boto3.resource('s3')
bucket = s3.Bucket('<bucket_name>')
prefix = '<object_key_prefix, if any>'

# note this based on UTC time
yesterday = datetime.fromisoformat(str(date.today() - timedelta(days=1)))

# function to retrieve Streaming Body from S3 with timedelta argument
def get_object(file_name):
    try:
        obj = file_name.get(IfModifiedSince=yesterday)
        return obj['Body']
    except:
        False


# obtain a list of s3 Objects with prefix filter
files = list(bucket.objects.filter(Prefix=prefix))

# Iterating through the list of files
# Loading streaming body into a file with the same name
# Printing file name and saving file
# Note skipping first file since it's only the directory

for file in files[1:]:
    file_name = file.key.split(prefix)[1] # getting the file name of the S3 object
    s3_file = get_object(file) # streaming body needing to iterate through
    if s3_file: # meets the modified by date
        print(file_name) # prints files not modified since timedelta
        try:
            with io.FileIO(file_name, 'w') as f:
                for i in s3_file: # iterating though streaming body
                    f.write(i)
        except TypeError as e:
            print(e, file)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM