首页 > 解决方案 > 您如何按 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 库可以转换?

标签: pythonpython-3.xamazon-web-servicesamazon-ec2boto3

解决方案


在你的代码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'))})


推荐阅读