cybertextron
cybertextron

Reputation: 10961

converting a JS Date to a Python date object

So I'm doing some Ajax trickery in the front page, and in the DJango backend, I send a JS Object, using AJAX... the format is: 'Tue Jan 28 2014 00:00:00 GMT-0800 (PST)' So I'm trying to convert it to a Python object:

     import datetime
 81    if request.is_ajax():
 82       datestr = request.POST['from_date']
 83       date = datetime.datetime.strptime(datestr, "%Y-%m-%dT%H:%M:%S.%fZ").date()
 84       message = date.__str__()
 85    else:
 86       message = "Not Ajax"
 87 
 88    return HttpResponse(message)

However I'm getting the following error:

time data 'Tue Jan 28 2014 00:00:00 GMT-0800 (PST)' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

How could I fix that? I'm looking forward a nicer solution that would avoid splitting and parsing the string ...

Upvotes: 1

Views: 1469

Answers (1)

RobG
RobG

Reputation: 147343

Given the format in the error message, then the client you can use ES5s Date.prototype.toISOString() to convert a Date object to an ISO 8601 string. You'll need a polyfill for browsers that don't have it.

Upvotes: 2

Related Questions