I think a better way to go about this would be to add a third block to the if statement.
Along the lines of if 'Z' in when, and then attempt "%Y-%m-%dT%H:%M:%S.%fZ" (milliseconds) and "%Y-%m-%dT%H:%M:%SZ" (no-milliseconds). Just make sure it comes before the if 'T' otherwise that block will get called instead.