python-3.x - 如何根据文件修改日期从 s3 存储桶下载文件?

标签 python-3.x amazon-s3 boto3

我想根据文件的上次修改日期从特定的 s3 存储桶下载文件。

我研究了如何连接boto3,并且有大量的代码和文档可用于无条件下载文件。我做了一个伪代码


def download_file_s3(bucket_name,modified_date)
    # connect to reseource s3
    s3 = boto3.resource('s3',aws_access_key_id='demo', aws_secret_access_key='demo')

    # connect to the desired bucket
    my_bucket = s3.Bucket(bucket_name)

    # Get files 
    for file in my_bucket.objects.all():



我想完成这个功能,基本上,传递一个修改日期,该函数返回 s3 存储桶中该特定修改日期的文件。

最佳答案

我有一个更好的解决方案或可以自动执行此操作的功能。只需传入 Bucket name 和 Download path name。

from boto3.session import Session
from datetime import date, timedelta
import boto3
import re


def Download_pdf_specifc_date_subfolder(bucket_name,download_path)
    ACCESS_KEY = 'XYZ'
    SECRET_KEY = 'ABC'
    Bucket_name=bucket_name

    # code to create a session 
    session = Session(aws_access_key_id=ACCESS_KEY,
              aws_secret_access_key=SECRET_KEY)
    s3 = session.resource('s3')
    bucket = s3.Bucket(Bucket_name)

    # code to get the yesterdays date
    yesterday = date.today() - timedelta(days=1)
    x=yesterday.strftime('20%y-%m-%d')
    print(x)

    #code to add the files to a list which needs to be downloaded
    files_to_downloaded = []
    #code to take all the files from s3 under a specific bucket
    for fileObject in bucket.objects.all():
        file_name = str(fileObject.key)
        last_modified=str(fileObject.last_modified)
        last_modified=last_modified.split()
        if last_modified[0]==x:
    # Enter the specific bucketname in the regex in place of Airports to filter only the particluar subfolder
            if re.findall(r"Airports/[a-zA-Z]+", file_name):
                files_to_downloaded.append(file_name)

     # code to Download into a specific Folder 
    for fileObject in bucket.objects.all():
        file_name = str(fileObject.key)
        if file_name in files_to_downloaded:
            print(file_name)
            d_path=download_path + file_name
            print(d_path)
            bucket.download_file(file_name,d_path)

Download_pdf_specifc_date_subfolder(bucket_name,download_path)

最终,该函数将在包含要下载的文件的特定文件夹中给出结果。

关于python-3.x - 如何根据文件修改日期从 s3 存储桶下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57877522/

相关文章:

aws-cloudformation - 如果已连接,则允许重新关联弹性 IP

时间序列的Python聚合

python - 导入tensorflow使python 3.6.5报错

amazon-s3 - 如何给目标bucket日志传送组WRITE和READ_ACP权限?

amazon-s3 - 使用 Cognito token 访问 S3 时获取 "AccessDenied"

node.js - 在 Amazon S3 上保存图像并使用 CloudFront 分发图像的最佳方式

Python AWS Boto3 : How to read files from S3 bucket?

amazon-web-services - boto3:创建具有 instanceprofile/IAM 角色的实例

python - 如何运行子进程命令以在后台 Python 中启动 nodejs 服务器

python - 如何将文件结构表示为 python 对象