使用 boto 获取 S3 对象的上次修改日期时间

问题描述 投票:0回答:13

我正在编写一个 Python 脚本,使用 boto 库将文件上传到

S3
。我只想上传 changed 文件(我可以通过其“上次修改”日期时间进行检查),但我找不到 Boto API 端点来获取上次修改日期。

python amazon-web-services amazon-s3 boto3 boto
13个回答
48
投票

这是一段 Python/boto 代码片段,它将打印存储桶中所有键的 last_modified 属性:

>>> import boto
>>> s3 = boto.connect_s3()
>>> bucket = s3.lookup('mybucket')
>>> for key in bucket:
       print key.name, key.size, key.last_modified
index.html 13738 2012-03-13T03:54:07.000Z
markdown.css 5991 2012-03-06T18:32:43.000Z
>>>

30
投票
当您使用 (S3)

LastModified

 python 对象时,
Boto3 返回
Object
的日期时间对象:

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Object.last_modified

您不需要执行任何曲折的字符串操作。

LastModified
与今天的日期进行比较 (Python3):

import boto3
from datetime import datetime, timezone

today = datetime.now(timezone.utc)

s3 = boto3.client('s3', region_name='eu-west-1')

objects = s3.list_objects(Bucket='my_bucket')

for o in objects["Contents"]:
    if o["LastModified"] == today:
        print(o["Key"])

您只需要知道

LastModifed
是时区感知的,因此您与之比较的任何日期也必须是时区感知的,因此:

datetime.now(timezone.utc)


18
投票

对于一个 s3 对象,您可以使用 boto 客户端的

head_object()
方法,该方法比针对一个对象的
list_objects_v2()
更快,因为返回的内容较少。返回值与所有 boto 响应类似,因此易于处理。

datetime

方法在对象修改时间附近提供了其他功能,可以在

head_object()
结果之后无需进一步调用即可利用这些功能。

看这个:

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.head_object

list_objects()



10
投票

从 s3 获取密钥后:

import boto3 s3 = boto3.client('s3') response = client.head_object(Bucket, Key) datetime_value = response["LastModified"]



4
投票

import time from time import mktime from datetime import datetime modified = time.strptime(key.last_modified, '%a, %d %b %Y %H:%M:%S %Z') #convert to datetime dt = datetime.fromtimestamp(mktime(modified))

这将为 S3 存储桶中的每个键提供一个 time.struct_time(tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst) 元组


3
投票
Django

django-storages,您可以在s3boto后端使用非官方API import time for key in bucket.get_all_keys(): time.strptime(key.last_modified[:19], "%Y-%m-%dT%H:%M:%S")

不幸的是,从 django-storages 1.1.5 开始,这给出了一个幼稚的日期时间。您需要使用 
>>> from storages.backends.s3boto import _parse_datestring >>> _parse_datestring("Fri, 20 Jul 2012 16:57:27 GMT") datetime.datetime(2012, 7, 21, 2, 57, 27)

创建一个

aware
版本: django.utils.timezone



2
投票
Resource

,您可以获得所有对象迭代器,然后检索>>> from django.utils import timezone >>> naive = _parse_datestring("Fri, 20 Jul 2012 16:57:27 GMT") >>> timezone.make_aware(naive, timezone.get_current_timezone()) datetime.datetime(2012, 7, 21, 2, 57, 27, tzinfo=<DstTzInfo 'Australia/Brisbane' EST+10:00:00 STD>)

last_modified
属性。
ObjectSummary

退货

import boto3 s3 = boto3.resource('s3') bk = s3.Bucket(bucket_name) [obj.last_modified for obj in bk.objects.all()][:10]



1
投票

[datetime.datetime(2020, 4, 17, 13, 23, 37, tzinfo=tzlocal()), datetime.datetime(2020, 4, 17, 13, 23, 37, tzinfo=tzlocal()), datetime.datetime(2020, 4, 17, 13, 23, 38, tzinfo=tzlocal()), datetime.datetime(2020, 4, 17, 13, 23, 38, tzinfo=tzlocal()), datetime.datetime(2020, 4, 17, 13, 23, 38, tzinfo=tzlocal()), datetime.datetime(2020, 4, 17, 13, 23, 37, tzinfo=tzlocal()), datetime.datetime(2020, 4, 17, 13, 23, 37, tzinfo=tzlocal()), datetime.datetime(2020, 4, 17, 13, 20, 20, tzinfo=tzlocal()), datetime.datetime(2020, 4, 20, 8, 30, 2, tzinfo=tzlocal()), datetime.datetime(2020, 3, 26, 15, 33, 58, tzinfo=tzlocal())]

resource

boto3.resource('s3').Object(<BUCKET_NAME>, <file_path>).last_modified

client



0
投票
链接:

boto3 链接
aws s3 列表对象
boto3.client('s3').head_object(<BUCKET_NAME>, <file_path>)['LastModified']



0
投票


0
投票
import boto3 from boto3.session import Session session = Session(aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY) s3 = session.resource('s3') my_bucket = s3.Bucket(BUCKET_NAME) for obj in my_bucket.objects.all(): print('{} | {}'.format(obj.key, obj.last_modified))

键对返回的对象列表进行排序

LastModified

您可以删除 
import boto3 s3_client = boto3.client('s3') s3_response = s3_client.list_objects(Bucket=BUCKET_NAME) sorted_contents = sorted(s3_response['Contents'], key=lambda d: d['LastModified'], reverse=True) sorted_contents[0].get('Key')

标志以获得最早修改的对象。您还可以按对象的

reverse=True
或您想要的任何其他属性进行排序。
    


0
投票

使用

Size

列出对象,然后从内容中获取密钥

s3.list_objects_v2(Bucket=Your_bucket_name)
LastModified



0
投票

import boto3 import json import datetime s3 = boto3.client('s3') def lambda_handler(event, context): bucket = Your-bucket-name try: listdata = s3.list_objects_v2(Bucket=bucket) contents = listdata['Contents'] if "Contents" in listdata else [] for key in contents: lastmodified = str(key['LastModified']) print("lastmodified:", lastmodified)

© www.soinside.com 2019 - 2024. All rights reserved.