Convert custom strings to datetime format
<p>I have a list of date-time data strings that looks like this:</p>

<pre><code>list = ["2016-08-02T09:20:32.456Z", "2016-07-03T09:22:35.129Z"]
</code></pre>

<p>I want to convert this to the example format (for the first item):</p>

<pre><code>"8/2/2016 9:20:32 AM"
</code></pre>

<p>I tried this:</p>

<pre><code>from datetime import datetime
for time in list:
    date = datetime.strptime(time, '%Y %m %d %I %R')
</code></pre>

<p>But returns error:</p>

<blockquote>
  <p>ValueError: 'R' is a bad directive in format '%Y %m %d %I %R'</p>
</blockquote>

<p>Thanks for any help!</p>

<p>You have several problems in you code:</p>

<ul>
<li><code>%R</code>doesn't seem to be a <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">correct directive</a> (that's your error, I think you are looking for <code>%p</code>).</li>
<li>the format in strptime is the format of your input, not the output</li>
<li>you are using <code>list</code> and <code>time</code> as a name variable which is bad ;]</li>
</ul>

<p>So, you could for first convert you time to a correct datetime object:</p>

<pre><code>&gt;&gt;&gt; t='2016-08-02T09:20:32.456Z'
&gt;&gt;&gt; d=datetime.strptime(t, "%Y-%m-%dT%H:%M:%S.%fZ")
&gt;&gt;&gt; d
datetime.datetime(2016, 8, 2, 9, 20, 32, 456000)
</code></pre>

<p>And then convert this object to a string with strftime</p>

<pre><code>&gt;&gt;&gt; datetime.strftime(d, "%m/%d/%Y %I:%M:%S %p")
'08/02/2016 09:20:32 AM'
</code></pre>

python date converter