Skip to content

Instantly share code, notes, and snippets.

@manimike00
Last active June 28, 2019 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manimike00/35dca49b635089c0c6b4e488f86c3247 to your computer and use it in GitHub Desktop.
Save manimike00/35dca49b635089c0c6b4e488f86c3247 to your computer and use it in GitHub Desktop.
Overall Uptime Time of EC2 instances in Running State
#### Requirements
#### AWSCLI
#### Must execute aws configure command before Running the Script
import boto3
import datetime
import itertools
client = boto3.client("ec2")
response = client.describe_instances()
loop1 = []
loop2 = []
loop3 = []
for reservations in response["Reservations"]:
for instances in reservations["Instances"]:
if instances["State"]["Name"] == "running" or instances["State"]["Name"] == "pending":
ids = instances["InstanceId"]
loop3.append(ids)
ins = instances["LaunchTime"]
time = str(ins)
t1 = ' '+time[11:18]
y1 = time[0:4]
m1 = time[5:7]+'-'
d1 = time[8:10]+'-'
at1 = (m1+d1+y1+t1)
loop1.append(at1)
now = datetime.datetime.utcnow()
time1 = str(now)
t2 = ' '+time1[11:18]
y2 = time1[0:4]
m2 = time1[5:7]+'-'
d2 = time1[8:10]+'-'
at2 = (m2+d2+y2+t2)
loop2.append(at2)
from datetime import datetime
date_format = "%m-%d-%Y %H:%M:%S"
for (x,y,z) in zip(loop1,loop2,loop3):
time1 = datetime.strptime(x, date_format)
time2 = datetime.strptime(y, date_format)
diff = time2 - time1
days = diff.days
days_to_hours = days * 24
diff_btw_two_times = (diff.seconds) / 3600
overall_hours = format((days_to_hours + diff_btw_two_times),'.2f')
print (str(overall_hours) + ' hours for '+ z);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment