1

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 ...

cybertextron
  • 10,547
  • 28
  • 104
  • 208
  • do you have an option to change the date format sent? If yes, I would say change it to epoch.. – Kiran Jan 31 '14 at 02:06
  • @Kiran how? I could easily parse the string, but I'm trying to avoid it – cybertextron Jan 31 '14 at 02:07
  • @mhlester not a duplicate ... problems are similar, but different – cybertextron Jan 31 '14 at 02:09
  • sorry you're right. retracted – mhlester Jan 31 '14 at 02:10
  • I am not fully aware of how python works, but in javascript, you can get epoch by calling date.getTime()/1000. This answer `http://stackoverflow.com/questions/12458595/convert-epoch-timestamp-in-python` talks about converting epoch to needed format. I thought you have date object in your javascript based on what you are receiving. – Kiran Jan 31 '14 at 02:14
  • @Kiran—good approach, but the javascript epoch is 1970-01-01T00:00:00Z. *getTime* returns a [time value](http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.1) that is milliseconds since the epoch. – RobG Jan 31 '14 at 02:25
  • @RobG that is correct. that's the reason I mentioned date.getTime()/1000. However, looks like python datetime is also taking in milliseconds in which case /1000 may not even be needed – Kiran Jan 31 '14 at 02:31

1 Answers1

2

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.

RobG
  • 142,382
  • 31
  • 172
  • 209