Sha*_*ash 5 python amazon-s3 boto aws-lambda
这里的要求是在源存储桶中我们接收历史每日文件。文件的格式为 -
源桶 -
s3://sourcebucket/abc/111111_abc_1180301000014_1-3_1180301042833.txt
s3://sourcebucket/abc/111111_cde_1180302000042_2-3_1180302042723.txt
Run Code Online (Sandbox Code Playgroud)
这些是示例值,因为我无法发布确切的文件名 -
111111_abc_1180301000014_1-3_1180301042833.txt
其中 1180301000014 是日期和时间 180301 - 日期 2018 年 3 月 1 日 000014 是小时、分钟和秒 - hhmmss
一旦我们收到 3 月 1 日的所有每小时文件,我们需要将这些文件复制到另一个存储桶,然后进行进一步处理。目前,复制部分工作正常。它将源存储桶中存在的所有文件复制到目标。但是,我不确定如何应用过滤器,以便它首先仅选择 3 月 1 日的文件并将其复制到另一个存储桶。然后它应该按顺序选择剩余的文件。
Python 脚本 -
import boto3
import json
s3 = boto3.resource('s3')
def lambda_handler(event, context):
bucket = s3.Bucket('<source-bucket>')
dest_bucket = s3.Bucket('<destination-bucket>')
for obj in bucket.objects.filter(Prefix='abc/',Delimiter='/'):
dest_key = obj.key
print(dest_key)
s3.Object(dest_bucket.name, dest_key).copy_from(CopySource = {'Bucket': obj.bucket_name, 'Key': obj.key})
Run Code Online (Sandbox Code Playgroud)
我不太精通 python。事实上,这是我的第一个 python 脚本。任何指导表示赞赏。
您可以提取文件名的日期字符串部分(最好通过在“_”上拆分字符串)并将其传递到处理函数中,例如:
from datetime import datetime as dt
def parse_date(date_string):
form = "%y%m%d%H%M%S"
date = dt.strptime(date_string, form)
#dt.utcnow() will return a UTC representation of the current time
diff = dt.now() - date
if diff.days >= 1:
return False
return True
#False
print(parse_date("180301000014"))
#True as of the date of this post
print(parse_date("180606000014"))
Run Code Online (Sandbox Code Playgroud)
您可以查看https://docs.python.org/3/library/datetime.html了解有关在 Python 中处理日期的更多信息。您还需要考虑时区。
要按天匹配目标日期:
def by_target_date(date_string, target_date):
form = "%y%m%d%H%M%S"
date = dt.strptime(date_string, form)
if date > target_date:
#Check that days match and that month and year are the same
if date.day == target_date.day and (date - target_date).days <= 1:
return do_things()
if date.day == target_date.day and (target_date - date).days <= 1:
return do_things()
Run Code Online (Sandbox Code Playgroud)