我只想使用 boto3 从 S3 存储桶中检索特定前缀中的 last_modified 密钥。
# 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")
使用此代码,当前结果不会输出最后修改的密钥。我尝试将 limit() 增加到 limit(10),但没有成功。
--更新开始--
也许,在 S3 中创建带有日期前缀的对象可能会更好。
{桶}/yyyy/mm/dd/{对象}
示例: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
date.
请确保您位于正确的区域作为存储桶。还last_modified
is in 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
邮件已发送
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)