Compare start time of EC2 instance and current time in python

I am fetching start_time from EC2 instance, it returns unicode string like this:

2014-12-22T08: 46: 10.000Z

I am using dateutil parser to convert it to datetime with

launch_time = parser.parse(instance.launch_time)

      

so I get lunch_time after transformation like this:

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

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

I am getting current_time with:

current_time = datetime.datetime.now()

      

and I get 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 to be 180 minutes (3 hours). But I got this error:

TypeError: cannot subtract time with smallest offset and offset times

I think there is an obvious difference between these two timestamps. I need to compare date and time exactly to see how long it has been running. I couldn't find the correct way to solve this problem. Any thoughts are appreciated!

+3


source to share


2 answers


You can specify the timezone you want from now()

as shown below:

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



Then your subtraction should work, since both will know about the timezone.

Edit: I should note that you can put any timezone object you want in now()

and it will work fine. now()

converts the time to whatever time zone you go through. The important part is to just make sure that if you add / subtract datetime objects that they have timezones (or they both don't have timezones).

+7


source


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)

      



0


source







All Articles