Skip to main content
 首页 » 编程设计

python之如何使用 boto3 仅检索 S3 中的 last_modified 键

2024年12月31日8rubylouvre

我只想从我的 S3 存储桶中检索 last_modified 键,使用 boto3 在特定前缀中。

# Get Today's date 
today = datetime.date.today() 
 
# Get Objects date 
s3 = boto3.resource('s3',region_name=AWS_REGION) 
bucket = s3.Bucket('xxx') 
objs = bucket.objects.filter(Prefix='yyyy').limit(1) 
 
def get_object_check_alarm(): 
  try: 
    for obj in objs: 
        print(obj) 
        lastobjectdate = (obj.last_modified).date() 
  except botocore.exceptions.ClientError as e: 
    error_code = e.response['Error']['Code'] 
    if error_code == '404': 
        print("There is no file") 
 
  # Compare with defined date 
  if today == lastobjectdate: 
    print(today) 
    print(lastobjectdate) 
    print("OK, lastest file comes from today") 
  else: 
    print(today) 
    print(lastobjectdate) 
    print("Mail sent") 

使用这段代码,当前结果不输出最后修改的key。我尝试将 limit() 增加到 limit(10),但没有成功。

请您参考如下方法:

--更新开始--

或许,在 S3 中创建带有日期前缀的对象可能会更好。

{bucket}/yyyy/mm/dd/{object}

示例:myS3bucket/2018/12/29/myfile.txt

通过这种方法,您的查询变得很简单,可以很容易地查明您是否有特定日期的任何文件,而且您检索到的文件列表数量也变得很短。

prefix="/"+str(today.year)+"/"+str(today.month)+"/"+str(today.day)+"/" 
objs = bucket.objects.filter(Prefix=prefix).all() 

--更新完成--

我不确定您是否提供了完整的代码,但上面的代码片段中存在一些缩进问题。我刚刚在下面进行了测试,它工作正常并且我得到了正确的 last_modified 日期。

请确保您在正确的区域作为存储桶。此外,last_modified 处于 UTC 时区,因此您的比较应该考虑这一点。

import boto3 
from datetime import date 
import botocore 
 
# Get Today's date 
today = date.today() 
# Get Objects date 
s3 = boto3.resource('s3',region_name='us-east-1') 
bucket = s3.Bucket('xxxx') 
prefix="/"+str(today.year)+"/"+str(today.month)+"/"+str(today.day)+"/" 
objs = bucket.objects.filter(Prefix=prefix).all() 
 
def get_object_check_alarm(): 
    try: 
        for obj in objs: 
            print(obj) 
            lastobjectdate = (obj.last_modified).date() 
    except botocore.exceptions.ClientError as e: 
        error_code = e.response['Error']['Code'] 
        if error_code == '404': 
            print("There is no file") 
 
# Compare with defined date 
    if today == lastobjectdate: 
        print(today) 
        print(lastobjectdate) 
        print("OK, lastest file comes from today") 
    else: 
        print(today) 
        print(lastobjectdate) 
        print("Mail sent") 
 
get_object_check_alarm() 

下面是输出。我在 EST 区,所以日期仍然是 12/28,但对象创建日期是 12/29,因为在创建对象时它在 UTC 区已经是 12/29。

s3.ObjectSummary(bucket_name='xxxx', key='yyyy/')

2018-12-28

2018-12-29

Mail sent