首页 > 解决方案 > datetime.datetime 对象不可下标

问题描述

我正在尝试为我的所有EC2实例获取卷创建时间。问题是boto3响应返回CreateTime为不可下标的日期时间对象。我尝试使用strftime()将对象转换为类型str,但我必须使用错误的语法或其他东西,因为我仍然遇到错误。以下是我的代码和回溯:

CODE:

import boto3
import json
import os
import csv
from datetime import datetime, date, time

ec2 = boto3.client('ec2')

ec2_response = ec2.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])

for item in ec2_response['Reservations']:
    instance_id = item['Instances'][0]['InstanceId']
    image_id = item['Instances'][0]['ImageId'] 
    create_time = item['Instances'][0]['BlockDeviceMappings'][0]['Ebs']['AttachTime'].strftime("%A, %d. %B %Y %I:%M%p")
    print(instance_id,image_id,create_time)

Traceback:

    create_time = item['Instances'][0]['BlockDeviceMappings'][0]['Ebs']['AttachTime'][0].strftime("%A, %d. %B %Y %I:%M%p")
TypeError: 'datetime.datetime' object is not subscriptable

标签: jsonpython-3.xdatetimeboto3

解决方案


首先,

item['Instances'][0]['BlockDeviceMappings'][0]['Ebs']['AttachTime']

不应该是一个列表。它是此处文档中的一项,也是以下 aws cli 命令返回的 JSON 中的一项:

aws --region us-east-1 ec2 describe-instances

我怀疑当你[0]

item['Instances'][0]['BlockDeviceMappings'][0]['Ebs']['AttachTime'][0]

这行代码成功完成,并list index out of range从 for 循环的后续迭代中引发。

如果不运行代码,很难知道为什么,但是例如,像这种情况下没有卷的实例会导致该行失败。

您可以像这样调试以检查有问题的数据:

try:
    create_time = item['Instances'][0]['BlockDeviceMappings'][0]['Ebs']['AttachTime'].strftime("%A, %d. %B %Y %I:%M%p")
except Exception as e:
    import pdb; pdb.set_trace()

或者如果没有附加到外壳上:

try:
    create_time = item['Instances'][0]['BlockDeviceMappings'][0]['Ebs']['AttachTime'].strftime("%A, %d. %B %Y %I:%M%p")
except Exception as e:
    print("Dumping offending item:")
    print(item)
    raise e

其次,虽然这AttachTime可能适合您的用例,但不一定是创建卷的时间,因为它们可以创建然后附加到实例。如果您需要实际创建时间,则需要再次调用describe_volume_status并使用该CreateTime字段。


推荐阅读