json - 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
解决方案
首先,
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
字段。
推荐阅读
- javascript - 获取第一个非空 regex.exec() 捕获组
- java - UDP 数据包重新排序
- jquery - angular2 使用 PrimeNG-Scheduler 实现 FullCalendar-Scheduler - 资源未显示
- python - 我怎样才能生成这个?
- ethereum - Solidity: try to make mintable token contract, but doesn't work
- monaco-editor - 点击获取 Monaco Editor CodeLens 信息
- scala - 为什么在 Scala 中使用 foreach 而不是 onSuccess 进行回调?
- opengl - 共享 VAO 的元素缓冲区对象大小
- java - 当您不知道数据库中有什么时如何使用 Hibernate
- angular - Angular js 2 'node_modules/rxjs/Observable"' 没有导出的成员 'Observable'。导入 Observable