2

尝试保存/测试此 Lambda Boto3 函数时,我遇到了一个非常烦人的错误。关于这个问题还有其他线程,但我花了大约 2 个小时试图调试它,但无法弄清楚我做错了什么(这可能很明显)。任何帮助,将不胜感激!

{
  "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
    }
4

1 回答 1

1

launch-time属性已经是一个日期时间属性。你不需要解析它。

参考: https ://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html

于 2019-12-07T10:57:09.540 回答