Search code examples
pythondatesalesforcesoqlsimple-salesforce

passing a variable in SOQL select statement with python and simple-salesforce


I am trying to pass a variable into SOQL statement, I am using simple_salesforce library. I only need to grab the data when CreateDate of the Opportunity is > than yesterday, yesterday's date is saved in last_run_day variable. Below is my code:

yesterday = date.today() + timedelta(days=-1)
last_run_date = yesterday.strftime("%Y-%m-%d"+"T"+"%H:%M:%S"+"Z")

sf_data = sf.query_all("SELECT ID, Name FROM Opportunity where probability > 0 AND CreatedDate > '%s' AND AdPoint_Id__c <> NULL ORDER BY AdPoint_Id__c" % last_run_date)
print(sf_data)

Gives me an error: field 'CreatedDate' must be of type dateTime and should not be enclosed in quotes", 'errorCode': 'INVALID_FIELD'


Solution

  • The method strftime actually returns a string. To find out the object type you can use the type method

    You can use this line of code in your program to check the type print(type(last_run_date)) it will return <class 'str'> which means its a string object.

    So in your query you cannot assign string to a datetime.

    You can try using the below code

    import datetime
    yesterday = datetime.datetime.now() + datetime.timedelta(days=-1)
    sf_data = sf.query_all("SELECT ID, Name FROM Opportunity where probability > 0 AND CreatedDate > '%s' AND AdPoint_Id__c <> NULL ORDER BY AdPoint_Id__c" % yesterday)
    print(sf_data)