【问题标题】:Sorting a list of ec2 instances pythonpython对ec2实例列表进行排序
【发布时间】:2021-10-29 23:56:10
【问题描述】:

我有一个 python 脚本,它打印出一个 ec2 实例列表,如下所示:

['i-06db4eb158ad0bdfd,2021-05-12 12:04:19+00:00,False', 'i-0f67cf99fb4536c3f,2020-10-14 13:32:23+00:00,asg-elk-', 'i-0539c8dfc839cbfda,2020-10-26 07:38:01+00:00,asg-standalone', 'i-0f285277529543462,2018-05-18 16:47:00+00:00,False', 'i-0d649cebdf54bd2f4,2020-03-12 10:07:07+00:00,asg-ddf', 'i-01734dfef0159c5c8,2020-10-20 13:05:27+00:00,asg-pro', 'i-0ff596f1dc01b61d8,2021-03-17 11:21:21+00:00,asg-base-test']

我希望能够根据 CreationDateTime 对列表进行排序。我使用了 python 内置函数 sorted() 但这似乎没有给我我需要的输出。

我的python脚本如下:

    response = ec2_client.describe_instances(
        MaxResults=10
    ) 
    instances = (len(response['Reservations']))

    instances_list = []
    for x in range(instances):

        # Get InstanceId
        instance_id = (response['Reservations'][x]
                       ['Instances'][0]['InstanceId'])
        # Get NetworkInterfacws AttatchTime
        network_interface_id = (
            response['Reservations'][x]['Instances'][0]['NetworkInterfaces'][0]['NetworkInterfaceId'])
        network_interface_details = ec2_client.describe_network_interfaces(
            NetworkInterfaceIds=[network_interface_id])
        networkinterface_id_attachedtime = network_interface_details[
            'NetworkInterfaces'][0]['Attachment']['AttachTime']
  

        # print results
        
       line = '{},{},{}'.format(
                instance_id, networkinterface_id_attachedtime, autoscaling_group_name)
            instances_list.append(line)
            sorted(instances_list)

【问题讨论】:

    标签: python python-3.x amazon-web-services datetime amazon-ec2


    【解决方案1】:

    sorted 采用key 参数,您可以使用该参数通过lambda 按日期排序:

    sorted(instances_list, key=lambda v: v.split(',')[1])
    

    【讨论】:

    • 哦,好的。因此 key 参数可用于按日期排序。我现在明白了。感谢您的建议
    • 当我将 MaxResults 更改为 100 时,我收到错误 IndexError: list index out of range。那会是它试图获取一个不存在的项目吗?
    猜你喜欢
    • 2011-04-29
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多