Validate an ISO-8601 datetime string in Python?
<p>I want to write a function that takes a string and returns <code>True</code> if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--<code>False</code> otherwise.</p>

<p>I have found <a href="https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1">other</a> <a href="https://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date-in-python/30696682#30696682">questions</a> that provide different ways of <em>parsing</em> datetime strings, but I want to return <code>True</code> in the case of ISO-8601 format only. Parsing doesn't help me unless I can get it to throw an error for formats that don't match ISO-8601.</p>

<p>(I am using the nice <a href="https://github.com/crsmithdev/arrow" rel="noreferrer">arrow</a> library elsewhere in my code. A solution that uses <code>arrow</code> would be welcome.)</p>

<hr>

<p><strong>EDIT:</strong> It appears that a general solution to "is this string a valid ISO 8601 datetime" does not exist among the common Python datetime packages.</p>

<p>So, to make this question narrower, more concrete and answerable, I will settle for a format string that will validate a datetime string in this form:</p>

<pre><code>'2016-12-13T21:20:37.593194+00:00'
</code></pre>

<p>Currently I am using:</p>

<pre><code>format_string = '%Y-%m-%dT%H:%M:%S.%f%z'
datetime.datetime.strptime(my_timestamp, format_string)
</code></pre>

<p>This gives:</p>

<pre><code>ValueError: time data '2016-12-13T21:20:37.593194+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'
</code></pre>

<p>The problem seems to lie with the colon in the UTC offset (<code>+00:00</code>). If I use an offset without a colon (e.g. <code>'2016-12-13T21:20:37.593194+0000'</code>), this parses properly as expected. This is apparently because <code>datetime</code>'s <code>%z</code> token <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="noreferrer">does not respect the UTC offset form that has a colon</a>, only the form without, even though <a href="https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC" rel="noreferrer">both are valid per the spec</a>.</p>