-1

I'm trying to write some code that will filter records from SalesForce that have a value in a field that is not before now. I have given up on trying to format a query that filters the results from SalesForce because not I have tried works and nothing anyone has suggested works (they all return "malformed request"). Although, I'm obviously open to suggestions on that front, too.

So, I have settled on something like this:

        now = datetime.now(pytz.UTC)
        disables = self.sssvc.query("select Name, Project__c, Ownerid, Id, DisableOn__c, User__c from PIXDisableUserTask__c WHERE Status__c = 'Pending'")
        for disable in disables[u'records']:
            disable_on = disable[u'DisableOn__c']
            if disable_on < now:
                continue
            else:
                disables.pop(disable)
            print
        return disables

But when I'm done I end up with two incompatible date formats for comparison. The problem is, I don't know how to convert the value of "now" from datetime and "disable_on" from SalesForce into time stamps that can be compared. What I get is something like:

now = 2015-07-29 19:19:07.322224+00:00
disable_on = u'2015-06-24T12:00:00.000+0000'

I know I need to change disable from a string to an actual datetime object in UTC, but I don't know what formula to use.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
Daniel Dow
  • 487
  • 1
  • 7
  • 20

1 Answers1

4

For Python 3.x , you can use the following format -

%Y-%m-%dT%H:%M:%S.%f%z

Example/Demo -

>>> import datetime
>>> datetime.datetime.strptime(u'2015-06-24T12:00:00.000+0000','%Y-%m-%dT%H:%M:%S.%f%z')
datetime.datetime(2015, 6, 24, 12, 0, tzinfo=datetime.timezone.utc)

You can also use the dateutil.parser method given below.


For Python 2.x , the '%z' directive is not implemented in Python 2.x (Atleast not in my Python 2.6) , but you can use dateutil.parser.parse() for parsing the date -

>>> import dateutil.parser
>>> dateutil.parser.parse(u'2015-06-24T12:00:00.000+0000')
datetime.datetime(2015, 6, 24, 12, 0, tzinfo=tzutc())

Note - You can use dateutil in Python 3 as well.


So for Python 2.x , your code would look like -

import dateutil.parser
now = datetime.now(pytz.UTC)
disables = self.sssvc.query("select Name, Project__c, Ownerid, Id, DisableOn__c, User__c from PIXDisableUserTask__c WHERE Status__c = 'Pending'")
for disable in disables[u'records']:
    disable_on = dateutil.parser.parse(disable[u'DisableOn__c'])
    if disable_on < now:
        continue
    else:
        disables.pop(disable)
    print
return disables
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176