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"]
]
)
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.
Try like this, you have to make sure pytz installed :
import pytz
utc=pytz.UTC
launchTime = utc.localize(launchTime)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With