How to sort stopped EC2s by time using "state_transition_reason" variable? Python Boto3
<p>I am seeing a steep increase on my AWS account costs. The largest cost items are: <strong>EC2: 67% RDS: 12%</strong></p>

<p>I have more than 50 stopped EC2s. One of them has been sitting there in a stopped state from September of the year 2015.</p>

<p>I found the way to get the stopped time of EC2s using variable called:</p>

<blockquote>
  <p>state_transition_reason</p>
</blockquote>

<p>Here how the code looks:</p>

<pre><code>import boto3

session = boto3.Session(region_name="us-east-1")
ec2 = session.resource('ec2')

instances = ec2.instances.filter(
            Filters=[{'Name': 'instance-state-name', 'Values': ['stopped']}])

count = 0

for i in instances:
   print "{0}, {1}, {2}".format( i.id, i.state_transition_reason, i.state['Name']) 
   count +=1

print count
</code></pre>

<p>It prints out the following information:</p>

<pre><code>i-pll78233b, User initiated (2016-07-06 21:14:03 GMT), stopped
i-tr62l5647, User initiated (2015-12-18 21:35:20 GMT), stopped
i-9oc4391ca, User initiated (2016-03-17 04:37:46 GMT), stopped
55
</code></pre>

<p><strong>My question is</strong>: How can I sort instances (EC2s) by their time being stopped. In my example I would love to see the output in the following order starting from year 2015 accordingly:</p>

<pre><code>i-tr62l5647, User initiated (2015-12-18 21:35:20 GMT), stopped
i-9oc4391ca, User initiated (2016-03-17 04:37:46 GMT), stopped
i-pll78233b, User initiated (2016-07-06 21:14:03 GMT), stopped
55
</code></pre>

<p>Thanks.</p>

<p>As long as the User initiated part never varies, we can simply sort the instances by state_transition_reason:</p>

<pre><code>sortedInstances = sorted(instances, key=lambda k: k.state_transition_reason) 
</code></pre>

python amazon-web-services amazon-ec2 aws-lambda boto3