使用列表对象数据结果来确定哪些文件已过期



我在AWS Lambda中启动了一个python脚本(非常基础(。我在几次尝试后得到了结果,现在我正试图扫描数据以确定";LastModified";日期超过4小时(基于当前日期和时间(。

有什么简单的方法吗

import boto3
import os
from datetime import datetime
def lambda_handler(event, context):
s3 = boto3.client('s3')
bucket = 'mybucket'
resp = s3.list_objects_v2(Bucket=bucket, Prefix='JSON/')
print(resp['Contents'])

这是一个响应示例(dicts列表(

[{'Key': 'JSON/File1.json', 'LastModified': datetime.datetime(2019, 5, 28, 18, 11, 42, tzinfo=tzlocal()), 'ETag': '"d41d8cd98f00b204e9800998ecf8427e"', 'Size': 0, 'StorageClass': 'STANDARD'}, {'Key': 'JSON/File2.json', 'LastModified': datetime.datetime(2020, 8, 6, 12, 55, 9, tzinfo=tzlocal()), 'ETag': '"e8534a11ac08968619c05e28641a09b8"', 'Size': 7600141, 'StorageClass': 'STANDARD'}, {'Key': 'JSON/File3.json', 'LastModified': datetime.datetime(2020, 8, 6, 12, 56, 9, tzinfo=tzlocal()), 'ETag': '"bac4bfc4daa1f4a4982b9ec0c5f11c62"', 'Size': 38430159, 'StorageClass': 'STANDARD'}

这应该适用于您向我展示的dict列表。首先,我在使用tzlocal((时遇到了问题。我必须将datetime.now((对象的tzinfo也设置为tzlocal(((reference(,然后它就工作了。希望它能帮助你:

import datetime
from dateutil.tz import tzlocal
data = [
{'Key': 'JSON/File1.json', 'LastModified': datetime.datetime(2019, 5, 28, 18, 11, 42, tzinfo=tzlocal()), 'ETag': '"d41d8cd98f00b204e9800998ecf8427e"', 'Size': 0, 'StorageClass': 'STANDARD'},
{'Key': 'JSON/File2.json', 'LastModified': datetime.datetime(2020, 8, 6, 12, 55, 9, tzinfo=tzlocal()), 'ETag': '"e8534a11ac08968619c05e28641a09b8"', 'Size': 7600141, 'StorageClass': 'STANDARD'},
{'Key': 'JSON/File3.json', 'LastModified': datetime.datetime(2020, 8, 6, 12, 56, 9, tzinfo=tzlocal()), 'ETag': '"bac4bfc4daa1f4a4982b9ec0c5f11c62"', 'Size': 38430159, 'StorageClass': 'STANDARD'}
]
filtered = list(filter(lambda x: x["LastModified"] < (datetime.datetime.now().replace(tzinfo=tzlocal()) - datetime.timedelta(hours=4)), data))
print(filtered)
#[{'Key': 'JSON/File1.json', 'LastModified': datetime.datetime(2019, 5, 28, 18, 11, 42, tzinfo=tzlocal()), 'ETag': '"d41d8cd98f00b204e9800998ecf8427e"', 'Size': 0, 'StorageClass': 'STANDARD'}]

最新更新