title: Python convert string to datetime for comparison to datetime object
body: <p>I have a string <code>lfile</code> with a datetime in it (<code>type(lfile)</code> gives <code>&lt;type 'str'&gt;</code>) and a Python datetime object <code>wfile</code>. Here is the code:</p>
  
  <pre><code>import os, datetime
  lfile = '2005-08-22_11:05:45.000000000'
  time_w = os.path.getmtime('{}\\{}.py' .format('C:\Temp_Readouts\RtFyar','TempReads.csv'))
  wfile = datetime.datetime.fromtimestamp(time_w)
  </code></pre>
  
  <p><code>wfile</code> contains this <code>2006-11-30 19:08:06.531328</code> and <code>repr(wfile)</code> gives:</p>
  
  <pre><code>datetime.datetime(2006, 11, 30, 19, 8, 6, 531328)
  </code></pre>
  
  <p><strong>Problem:</strong></p>
  
  <p>I need to:</p>
  
  <ol>
  <li>convert <code>lfile</code> into a Python datetime object</li>
  <li>compare <code>lfile</code> to <code>wfile</code> and determine which datetime is more recent</li>
  </ol>
  
  <p>For 1.:</p>
  
  <p>I am only able to get a partial solution using <code>strptime</code> as per <a href="https://stackoverflow.com/questions/698223/how-can-i-parse-a-time-string-containing-milliseconds-in-it-with-python">here</a>. Here is what I tried:</p>
  
  <pre><code>lfile = datetime.datetime.strptime(linx_file_dtime, '%Y-%m-%d_%H:%M:%S')
  </code></pre>
  
  <p>The output is:</p>
  
  <pre><code>`ValueError: unconverted data remains: .000`
  </code></pre>
  
  <p><em>Question 1</em></p>
  
  <p>It seems that <code>strptime()</code> <a href="https://stackoverflow.com/questions/10611328/format-nanoseconds-in-python">cannot</a> handle the nano seconds. How do I tell <code>strptime()</code> to ignore the last 3 zeros?</p>
  
  <p>For 2.:</p>
  
  <p>When I use <code>type(wfile)</code> I get <code>&lt;type 'datetime.datetime'&gt;</code>. If both <code>wfile</code> and <code>lfile</code> are Python datetime objects (i.e. if step 1. is successful), then would <a href="https://stackoverflow.com/questions/8142364/how-to-compare-two-dates">this</a> work?:</p>
  
  <pre><code>if wtime &lt; ltime:
      print 'Linux file created after Windows file'
  else:
      print 'Windows file created after Linux file'
  </code></pre>
  
  <p><em>Question 2</em></p>
  
  <p>Or is there some other way in which Python can compare datetime objects to determine which of the two occurred after the other?</p>