![](/img/trans.png)
[英]Boto + Python + AWS S3: How to get last_modified attribute of specific file?
[英]How to retrieve only the last_modified key in S3 with boto3
我只想從我的 S3 存儲桶中使用 boto3 檢索特定前綴中的 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 中創建帶有日期前綴的對象可能會更好。
{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
郵件已發送
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.