Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two Python 3 datetime objects returns "can't compare offset-naive and offset-aware datetimes: TypeError"

I am trying to compare the time of an AWS EC2 instance object that is of type datetime with another datetime being represented as datetime.datetime.now. The line of code in question looks like,

if launchTime < datetime.datetime.now()-datetime.timedelta(seconds=20):

Where launchTime is of type datetime. However when I run it I get the error

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

And I'm unsure of how to convert launchTime in such a way where I can successfully compare it.

Edited fixed code below -----------------------------------------

if launchTime.replace(tzinfo=None) < datetime.datetime.now()-datetime.timedelta(minutes=4):

Full code as well in case any future people find it of value. It's Python 3 to stop EC2 instances that have been running for an "x" amount of time. In this case if an instance is running for five minutes. Terminate it. The lambda itself is set up with Cloudwatch to run every 4 minutes as well.

import boto3
import time
import datetime

#for returning data about our newly created instance later on in fuction
client = boto3.client('ec2')

def lambda_handler(event, context):

response = client.describe_instances()
#for each instance currently running/terminated/stopped
for r in response['Reservations']:
    for i in r['Instances']:
        #if its running then we want to see if its been running for more then 3 hours. If it has then we stop it. 
        if i["State"]["Name"] == "running":
            launchTime = i["LaunchTime"]

            #can change minutes=4 to anything
            if launchTime.replace(tzinfo=None) < datetime.datetime.now()-datetime.timedelta(minutes=4):
                response = client.stop_instances(
                    InstanceIds=[
                        i["InstanceId"]
                    ]
                )
like image 740
jelidens Avatar asked May 10 '18 04:05

jelidens


2 Answers

The main problem is that I'm assuming launchTime is timezone aware, whereas datetime.now() is not (datetime.now().tzinfo == None).

There are a couple ways to solve this, but the easiest would be to remove the tzinfo from launchTime: if launchTime.replace(tzinfo=None) < datetime.datetime.now()-datetime.timedelta(seconds=20) should do the trick.

Alternatively, you can convert your datetime objects to Unix timestamps and then you don't have to deal with timezone silliness.

like image 183
Demian Brecht Avatar answered Oct 30 '22 17:10

Demian Brecht


Try like this, you have to make sure pytz installed :

import pytz

utc=pytz.UTC
launchTime = utc.localize(launchTime) 
like image 4
Vikas Periyadath Avatar answered Oct 30 '22 19:10

Vikas Periyadath