I am getting a very annoying error when trying to save/test this Lambda Boto3 function. There are other threads here on this issue, but i have spent about 2 hours trying to debug this and can't figure out what i'm doing wrong (it's probably something obvious). Any help would be appreciated!
{
"errorMessage": "Parser must be a string or character stream, not datetime",
"errorType": "TypeError",
"stackTrace": [
" File \"/var/task/lambda_function.py\", line 35, in lambda_handler\n a = dateutil.parser.parse(instance.launch_time)\n",
" File \"/var/runtime/dateutil/parser/_parser.py\", line 1358, in parse\n return DEFAULTPARSER.parse(timestr, **kwargs)\n",
" File \"/var/runtime/dateutil/parser/_parser.py\", line 646, in parse\n res, skipped_tokens = self._parse(timestr, **kwargs)\n",
" File \"/var/runtime/dateutil/parser/_parser.py\", line 722, in _parse\n l = _timelex.split(timestr) # Splits the timestr into tokens\n",
" File \"/var/runtime/dateutil/parser/_parser.py\", line 207, in split\n return list(cls(s))\n",
" File \"/var/runtime/dateutil/parser/_parser.py\", line 76, in __init__\n '{itype}'.format(itype=instream.__class__.__name__))\n"
]
}
import json
import boto3
import time
import datetime
import dateutil
from dateutil.parser import parse
def lambda_handler(event, context):
detailDict = event["detail"]
ec2 = boto3.resource('ec2')
instanceId = str(detailDict["instance-id"])
instance = ec2.Instance(instanceId)
instanceState = instance.state
a = dateutil.parser.parse(instance.launch_time)
b = current_time = datetime.datetime.now(launch_time.tzinfo)
# returns a timedelta object
c = a-b
print('Difference: ', c)
minutes = c.seconds / 60
print('Difference in minutes: ', minutes)
Message=str(instanceId)+" is "+str(instanceState["Name"])
return {
'statusCode': 200,
'body': Message
}
The launch-time
property is already a datetime property. You do not need to parse it.
Reference: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html