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>Your first problem is that the input has a different format. But unfortunatelly for you, that is not your only problem and it wouldn't work even if you fixed that.</p>

<p>The truth is that even the first format would fail with a different timezone:</p>

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

<p>fails with:</p>

<pre><code>ValueError: time data 'Sun, 04 Sep 2016 07:13:06 IST' does not match format '%a, %d %b %Y %H:%M:%S %Z'
</code></pre>

<p><code>strptime</code> just isn't good enough for handling timezones.</p>

<p>Check these answers for your options:</p>

<ul>
<li><a href="http://stackoverflow.com/a/12282040/389289">Answer to <em>Convert timestamps with offset to datetime obj using strptime</em></a></li>
<li><a href="http://stackoverflow.com/a/8525115/389289">Answer to <em>Python strptime() and timezones?</em></a></li>
</ul>

javascript python django datetime