Javascript date string to python datetime object
<p>The current datetime is passed via an <strong>ajax request</strong> to a <strong>django backend</strong> where it will be stored in the database. To store it in the database, the date must first be converted to a <code>datetime</code> object which can be done for a date of the in UTC format (Eg. <code>Sun, 04 Sep 2016 07:13:06 GMT</code>) easily by the following statement:</p>

<pre><code>&gt;&gt;&gt; from datetime import datetime
&gt;&gt;&gt; datetime.strptime("Sun, 04 Sep 2016 07:13:06 GMT", "%a, %d %b %Y %H:%M:%S %Z")
</code></pre>

<p>However in such a method, there is no preservation of the user's timezone.</p>

<p>The javascript <code>Date</code> constructor call i.e. <code>new Date()</code> returns a date in the following format:</p>

<pre><code>Sun Sep 04 2016 12:38:43 GMT+0530 (IST)
</code></pre>

<p>which gives an error when converting to datetime object.</p>

<pre><code>&gt;&gt;&gt; datetime.strptime("Sun, 04 Sep 2016 07:13:06 GMT+0530 (IST)", "%a, %d %b %Y %H:%M:%S %Z")

ValueError: time data 'Sun Sep 04 2016 12:46:07 GMT+0530 (IST)' does not match format '%a, %d %b %Y %H:%M:%S %Z'
</code></pre>

<p>1) How to resolve this problem?
2) Is there any better way to approach it?</p>

<p>You can use python's <code>dateutil</code> module to parse your date.</p>

<pre><code>from dateutil import parser
parser.parse("Sun, 04 Sep 2016 07:13:06 GMT+0530 (IST)")
</code></pre>

<p>It gives the output as a datetime object:</p>

<pre><code>datetime.datetime(2016, 9, 4, 7, 13, 6, tzinfo=tzoffset(u'IST', -19800))
</code></pre>

javascript python django datetime