python - 您如何按 Boto 中的 CreationDate 字符串对 AMI 进行排序?
问题描述
使用 Boto 我有:
images = ec2_client.describe_images(
Owners=['self']
)
如何使用 CreationDate 键对这些图像进行排序?
当我尝试使用时:
print({image['CreationDate']: image['ImageId'] in sorted(images.items(), key=lambda image: image['CreationDate'])})
我明白了TypeError: tuple indices must be integers or slices, not str
我认为这是因为 CreationDate 是一个字符串。
也许有一些 Python 库可以转换?
解决方案
在你的代码image
中没有定义,所以它甚至不会运行。也是images.items()
不正确的。所以你的脚本失败不是因为CreationDate
是字符串。它应该是:
print({image['CreationDate']: image['ImageId'] for image in sorted(images['Images'], key=lambda image: image['CreationDate'])})
也CreationDate
采用允许将其排序为字符串的格式。但是,如果您真的想将字符串解析为,datetime
则可以执行以下操作:
from datetime import datetime
print({image['CreationDate']: image['ImageId'] for image in sorted(images['Images'], key=lambda image: datetime.strptime(image['CreationDate'], '%Y-%m-%dT%H:%M:%S.%f%z'))})
推荐阅读
- uwsgi - Web 应用程序的网关接口混淆
- ios - 如何将带有 cocopods 的 Xcode 项目添加到 github
- java - Chrome 驱动程序未将 chrome 驱动程序服务和功能设置为参数
- c# - 如何在c#中修复时间字符串
- css - 将鼠标悬停在另一个 div 上时,无法让 div 的不透明度为 1
- ruby-on-rails - 我想在我插入多个图像的相册控制器中删除单个图像。我怎样才能删除?
- python - SCS 和 MOSEK 求解器继续运行
- python - 使用具有多个值的字典过滤数据框
- c++ - C ++“<”小于运算符未按预期工作
- css - 我在我的 react js 中添加了背景图片。但它显示一个错误