Compare launch time of EC2 instance and current time in python

旧巷老猫 提交于 2019-12-23 13:58:08

问题


I extract the launch_time from EC2 instance, it returns a unicode string like this:

2014-12-22T08:46:10.000Z

I use dateutil parser to convert it to datetime with

launch_time = parser.parse(instance.launch_time)

so I get lunch_time after converted like this:

2014-12-22 08:46:10+00:00

And I want to compare this launchtime with current time to see how long this instance has been running.

I get current_time with:

current_time = datetime.datetime.now()

and I get it like this:

2014-12-22 11:46:10.527010

Now I have two timestamps, I have this function

def timeDiff(launch_time, current_time):
    running_time = current_time - launch_time
    return running_time.seconds/60

I expect the result would be 180 minutes (3 hours). But I got this error:

TypeError: can't subtract offset-naive and offset-aware datetimes

I think there's obvious difference between these two timestamps. I need to compare exactly date and time to see how long it has been running. I couldn't find a proper way to solve this. Any thoughts appreciated!


回答1:


You can specify the timezone you want from now() like the following:

current_time = datetime.datetime.now(launch_time.tzinfo)

Then your subtraction should work, as both of the times will be timezone aware.

Edit: I should note that you can put whatever timezone object you want in now() and it will work just fine. now() will convert the time to whatever timezone you pass. The important part is to simply ensure that if you're adding/subtracting datetime objects that they both have timezones (or they both lack timezones).




回答2:


import boto.ec2
from dateutil.parser import *
import subprocess
import datetime


instance_id = subprocess.check_output(['curl', '-s', 'http://169.254.169.254/latest/meta-data/instance-id'])

conn = boto.ec2.connect_to_region('ap-southeast-2',aws_access_key_id='Your_Key', aws_secret_access_key='Your_Secret')

reservations = conn.get_all_reservations(instance_ids=[instance_id])

for r in reservations:
    for instance in r.instances:
        lt_datetime = parse(instance.launch_time)
        lt_delta = datetime.datetime.now(lt_datetime.tzinfo) - lt_datetime
        uptime = str(lt_delta)
        print(uptime)


来源:https://stackoverflow.com/questions/27601551/compare-launch-time-of-ec2-instance-and-current-time-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!