How to get AWS Lambda remaining time using Python

To get the remaining time of a running AWS Lambda Function using Python you should check the context object and its get_remaining_time_in_millis function.

Here is a simple Lambda Python code to check the remaining time.

def lambda_handler(event, context):
  
  remaining_time = context.get_remaining_time_in_millis()
  
  print(remaining_time)

Here’s the output when I run the code in a Lambda function that has a timeout of 3 seconds.


The Output is in Milliseconds

If you noticed that the output above is 3000 when the timeout is 3 seconds, that is because the output is in Milliseconds.

It’s actually in the name of the function – context.get_remaining_time_in_millis().

If you want to convert the AWS Lambda remaining time to seconds then just divide it by 1,000 to its value in seconds.

Here is a Python code that will output the remaining time of Lambda in seconds.

def lambda_handler(event, context):
  
  remaining_time_in_millis = context.get_remaining_time_in_millis()
  
  remaining_time_in_seconds = remaining_time_in_millis/1000
  
  print(remaining_time_in_seconds)

Below is a screenshot of the output and it shows 2.999 instead of a number in thousands of milliseconds.


Multiple remaining time to Lambda Time Out

The example above only shows the number of milliseconds remaining at the very start of the run. It does not show what the output will look like if we get the value of context.get_remaining_time_in_millis() somewhere in between the start and the time out of the Lambda Function.

So I created a Lambda Python Code below to print the remaining time every after a sleep of 1 second. It will only stop when the Lambda function times out.

For fun, I adjusted the Lambda Function’s timeout to 10 seconds.

from time import sleep

def lambda_handler(event, context):
    
  while True:
    remaining_time = context.get_remaining_time_in_millis()
    
    print(remaining_time)
    
    sleep(1) # delay of 1 second

In the output below, we can see that the remaining_time was printed approximately every after 1 second until Lambda timed out.


With this, I hope you have learned how to get the remaining time of a running AWS Lambda Function using Python.

Let me know what you think in the comments below.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.