Python - GCP Cloud Function issue with getting yesterdays date

Viewed 34

I have a requirement of getting yesterdays date in my GCP Cloud Function which is written Python 3.9

This is the snippet I am using

from datetime import datetime, timedelta
cur_dt = datetime.today()
str_dt = str((datetime.today() - timedelta(1)).strftime('%Y-%m-%d'))
print(cur_dt)
print(str_dt)

This is working fine in Jupyter notebook. But if I place this same code in my cloud function, it fails to compile.

This is the error message I am getting: - Function failed on loading user code. This is likely due to a bug in the user code.

Would be of great help if anyone can help me fixing this error. This is strange and I dont understand why CLoud function isnt accepting something that is working fine in Jupyter notebook

Many Thanks in Advance.

1 Answers

As mentioned you need to follow the Cloud Functions schema which requires an entrypoint function that takes in the request parameter. Here is a codelab that walks through setting up a Cloud Function.

Your code should be updated to the following:

# imports 
from datetime import datetime, timedelta

# entrypoint function with request param
def get_time(request):
  cur_dt = datetime.today()
  str_dt = str((datetime.today() - timedelta(1)).strftime('%Y-%m-%d'))
  # can still print here if you want
  return str_dt

If you are going through the UI make sure to update the entrypoint field to be get_time or whatever you name your entrypoint function.

Related