【问题标题】:AWS Lambda Python script to iterate over S3 bucket and copy daily files to another S3 bucket用于迭代 S3 存储桶并将每日文件复制到另一个 S3 存储桶的 AWS Lambda Python 脚本
【发布时间】:2018-11-16 17:00:22
【问题描述】:

这里的要求是在源存储桶中我们接收历史每日文件。文件格式为 -

源存储桶-

s3://sourcebucket/abc/111111_abc_1180301000014_1-3_1180301042833.txt
s3://sourcebucket/abc/111111_cde_1180302000042_2-3_1180302042723.txt

这些是示例值,因为我无法发布确切的文件名 -

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})

我不是很精通python。事实上,这是我的第一个 python 脚本。任何指导表示赞赏。

【问题讨论】:

  • 您的代码需要获取“今天的日期”,减去一天,然后找到与当天匹配的文件名。但是,您需要注意时区 - 您对“一旦我们收到 3 月 1 日的所有文件”的定义是什么?文件使用什么时区?如果您在 EC2 实例上运行代码,它将使用 UTC 作为时区,除非您特别编写其他代码。
  • 这些是历史文件。我的代码将通过 Lambda 运行。

标签: python amazon-s3 aws-lambda boto


【解决方案1】:

您可以提取文件名的日期字符串部分(最好将字符串拆分为“_”)并将其传递给处理函数,例如:

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"))

您可以查看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()

【讨论】:

猜你喜欢
  • 2020-05-29
  • 2019-10-02
  • 1970-01-01
  • 2017-04-14
  • 2018-11-22
  • 2023-02-01
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
相关资源
最近更新 更多