2

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
    }
2
  • 1
    Instance.launch_time? May be already datetime? Commented Dec 7, 2019 at 8:44
  • 1
    That is correct, the instance.launcy_time is already datetime format. print(type(instance.launch_time)) <class 'datetime.datetime'> Commented Dec 7, 2019 at 9:26

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.