Python 3.x 如何根据文件修改日期从s3 bucket下载文件?
我想根据文件上次修改日期从特定的s3存储桶下载文件 我已经研究了如何连接boto3,有大量代码和文档可用于无条件下载该文件。我做了一个伪代码Python 3.x 如何根据文件修改日期从s3 bucket下载文件?,python-3.x,amazon-s3,boto3,Python 3.x,Amazon S3,Boto3,我想根据文件上次修改日期从特定的s3存储桶下载文件 我已经研究了如何连接boto3,有大量代码和文档可用于无条件下载该文件。我做了一个伪代码 def下载文件(存储桶名称、修改日期) #连接到重新源s3 s3=boto3.resource('s3',aws\u access\u key\u id='demo',aws\u secret\u access\u key='demo') #连接到所需的铲斗 my_bucket=s3.bucket(bucket_name) #获取文件 对于my_buck
def下载文件(存储桶名称、修改日期)
#连接到重新源s3
s3=boto3.resource('s3',aws\u access\u key\u id='demo',aws\u secret\u access\u key='demo')
#连接到所需的铲斗
my_bucket=s3.bucket(bucket_name)
#获取文件
对于my_bucket.objects.all()中的文件:
我想完成这个函数,基本上,传递一个修改日期。该函数返回s3存储桶中特定修改日期的文件。这是我的测试代码,它将打印对象的最后修改日期时间,这些对象的日期时间在我设置的日期时间之后
导入boto3
从日期时间导入日期时间
从日期时间导入时区
s3=boto3.resource('s3')
response=s3.Bucket(“”).objects.all()
答复项目:
obj=s3.Object(item.bucket\u名称,item.key)
如果obj.last_modified>datetime(2019,8,1,0,0,0,tzinfo=timezone.utc):
打印(对象最后一次修改)
如果你有一个具体的日期,那么
导入boto3
从日期时间导入日期时间,时区
s3=boto3.resource('s3')
response=s3.Bucket(“”).objects.all()
日期='20190827'#输入('将日期插入表格YYYYmmdd')
答复项目:
obj=s3.Object(item.bucket\u名称,item.key)
如果对象上次修改.strftime(“%Y%m%d”)==日期:
打印(对象最后一次修改)
将给出如下结果
2019-08-27 07:13:04+00:00
2019-08-27 07:13:36+00:00
2019-08-27 07:13:39+00:00
我有一个更好的解决方案或功能,可以自动做到这一点。只需传入Bucket名称和下载路径名称
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)
最终,该函数将在特定文件夹中给出结果,其中包含要下载的文件。因此,如果我想检查上次修改方法的特定日期。我可以像这样检查obj.last_modified==date对吗?这在函数格式中解决了我的确切问题。这将对其他人有很大帮助。