2
votes

Background : Triggering a CF via Cloud Scheduler: Image below: Its scheduled to run at 7 am Australia/Sydney time and trigger two cloud functions:

enter image description here

Cloud Function : Regions is us-central1. Code used :

# Global variable:

tz=pytz.timezone('Australia/Sydney')
naive_dt = datetime.now(tz=tz)
since = datetime.strftime(naive_dt - timedelta(1), '%Y-%m-%d') #yesterday's date 
until = datetime.strftime(naive_dt - timedelta(1), '%Y-%m-%d') #yesterday's date 

def honda_reporting_automation(event,context):

    print("New Day")
    print("current Function Execution date time",naive_dt)
    print("since",since)
    print("until",until)

Weird cloud function behaviour: 1. Though the cloud scheduler triggers the job at 7:00 am, and I have set the server timing to my local timing in my code, still the timing of execution differs.It takes US Timings(1 day lag) (Image below)

enter image description here

  1. 2nd Cloud function shows different time of start(a difference of 4 mins from 1st one) , though triggered at the same time by the same scheduler.

enter image description here

  1. When triggered manually via Cloud Scheduler using "Run now" option, they behave as expected and shows correct timings. (image 3)

enter image description here

anyone came across this weird behaviour ? and any idea how to resolve it ?

1

1 Answers

4
votes

What is the error here? you are asking the function to be excecuted at 7:00 AEDT and it's being executed at this time. The server where the Cloud Function runs is in US central so the log trowed by the system to stackdriver will reflect this timezone. Since Cloud Functions is a Serverless product you can't modify the timezone of the machine where the function is excecuted.

Also according to the pytz documentation you are not converting the time correctly.

You should use something similar to:

naive_dt = datetime.now(timezone(tz))

instead of:

naive_dt = datetime.now(tz=tz)

Here is an example of my code working:

from pytz import timezone
from datetime import datetime
import pytz

def hello_world(request):
    fmt = "%Y-%m-%d %H:%M:%S %Z%z"
    nowutc = datetime.now(timezone('UTC'))
    now_australia = nowutc.astimezone(timezone('Australia/Sydney'))
    print(now_australia.strftime(fmt))

    request_json = request.get_json()
    if request.args and 'message' in request.args:
        return request.args.get('message')
    elif request_json and 'message' in request_json:
        return request_json['message']
    else:
        return str(now_australia.strftime(fmt))

Log:

enter image description here