Home > OS >  AWS Lambda Python datetime.now() getting the latest deployment time
AWS Lambda Python datetime.now() getting the latest deployment time

Time:08-29

Crazy stuff!
https://mli5b6535jtcvi235pbsklo4sq0cwajd.lambda-url.sa-east-1.on.aws/

The code is just:

import json
from datetime import datetime
now = datetime.now()

def lambda_handler(event, context):

   return {
        'statusCode': 200,
        'body': json.dumps(str(now))
    }

It's returning 2022-08-27 22:32:59.792352, except I redeployed the function.

CodePudding user response:

To return the current time the datetime.now() function call would need to be inside the lambda_handler function as this will be called each time your lambda function is invoked. This can be used to your advantage when using third party SDK's or similar to avoid re-creating them on every invocation and only when the runtime is initiated.

The variable "now" will only be set when the lambda runtime is initiated either when new code is deployed or lambda scales the number of runtimes for your function. More information about the lifecycle of lambda functions https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html#runtimes-lifecycle-ib

The bellow would return the current time of when each request is made

import json
from datetime import datetime

def lambda_handler(event, context):
    now = datetime.now()
    return {
        'statusCode': 200,
        'body': json.dumps(str(now))
    }
  • Related