Object of type datetime is not JSON serializable

493    Asked by AndreaBailey in QA Testing , Asked on Apr 3, 2021

I'm new using Simple_Salesforce for Python and I'm trying to update a record of "Account" and one of the values that I need to update is a Date/Time value, but I'm receiving the error: "Object of type datetime is not JSON serializable" when I use the update method like this:

sf.Account.update(sf_id, {'variable1': value1, 'variable2_Date__c': datetime(2021, 2, 1, 1, 2, 3, tzinfo=timezone.utc)})

What am I doing wrong? Or what do I need to improve in order to do the update?

Answered by Cameron Oliver

To solve an object of type datetime that is not json serializable, you have to convert the Python datetime into a string that matches the very specific format accepted by Salesforce. Here's what I do in CumulusCI:

    def salesforce_from_datetime(d): """Create a Salesforce-style ISO8601 string from a Python datetime""" return d.strftime("%Y-%m-%dT%H:%M:%S.{}+0000").format( str(d.microsecond)[:3].ljust(3, "0") )

That does the ISO8601 formatting but also converts Python's microseconds into the milliseconds that the Salesforce API expects, with exactly three digits.



Your Answer

Interviews

Parent Categories