如何使用BotoPython从S3获取最新文件的最后修改日期



这是我的s3桶的结构

Bucket 1
Company A
File A-02/01/20
File A-01/01/20
File B-02/01/20
File B-01/01/20
Company B
File A-02/01/20
File A-01/01/20

我正试图转到Bucket 1>>导航到公司A文件夹,找到文件A的最新版本并打印修改日期,我想对文件B和公司B文件夹/文件A重复相同的步骤。我是S3和Boto3的新手,所以仍在学习。这就是我的代码到目前为止的

import boto3
from datetime import datetime, timezone
today = datetime.now(timezone.utc)
s3 = boto3.client('s3', region_name='us-east-1')
objects = s3.list_objects(Bucket='Bucket 1',Prefix = 'Company A'+'/File')
for o in objects["Contents"]:
if o["LastModified"] != today:
print(o["Key"] +" "+ str(o["LastModified"]))

这会打印出以下内容:

File A_2019-10-28.csv 2019-11-11 18:31:17+00:00 
File A_2020-01-14.csv 2020-01-14 21:17:46+00:00 
File A_2020-01-28.csv 2020-01-29 19:19:58+00:00

但我只想检查文件A_2020-01-28.csv并打印if=今天,文件B 也是如此

假设"文件A"的末尾总是有一个日期,则可以在前缀搜索中使用"A"部分。S3需要记住的一点是,不存在文件夹这样的东西。这是你在他们的密钥名称中使用"/"所暗示的。S3只适用于Buckets/Keys。

该文件的最新版本将是具有最新last_modified字段的版本。一种方法是对该属性上的对象列表("A"文件(进行排序:

from operator import attrgetter
objs = s3.Bucket('Bucket 1').objects.filter(Prefix='Company A/File A')
# sort the objects based on 'obj.last_modified'
sorted_objs = sorted(objs, key=attrgetter('last_modified'))
# The latest version of the file (the last one in the list)
latest = sorted_objs.pop()

举个例子:我按顺序创建了foo1.txt、foo2.txt、foo3.txt。那么foo10.txt,foo5.txt。foo5.txt是我最新的"foo"文件。

>>> b.upload_file('/var/tmp/foo.txt','foo10.txt')
>>> b.upload_file('/var/tmp/foo.txt','foo5.txt')
>>> [i.key for i in b.objects.all()]  ## no ordering
['foo.txt', 'foo10.txt', 'foo2.txt', 'foo3.txt', 'foo5.txt']
>>> f2 = sorted(b.objects.all(), key=attrgetter('last_modified'))
>>> f2
[s3.ObjectSummary(bucket_name='foobar', key='foo.txt'), s3.ObjectSummary(bucket_name='foobar', key='foo2.txt'), s3.ObjectSummary(bucket_name='foobar', key='foo3.txt'), s3.ObjectSummary(bucket_name='foobar', key='foo10.txt'), s3.ObjectSummary(bucket_name='foobar', key='foo5.txt')]
>>> f2.pop()
s3.ObjectSummary(bucket_name='foobar', key='foo5.txt')

有关Python排序的更多详细信息,请参阅:https://wiki.python.org/moin/HowTo/Sorting

差不多,但是if语句比较了两个不同的datetime对象,它们包含日期和时间-时间会有所不同。如果您只在日期之后,则将if更改为:

if o["LastModified"].date() != today.date():

适用于Python 3.6.9。

最新更新