Parsing an arbitrary ISO 8601 timestamp with minimal libraries
suggest changedatetime.fromisoformat() parses the ISO 8601 forms that isoformat() emits, including a space or T as the separator and, since Python 3.11, a Z suffix. strptime still needs an exact format. As a complication, converting a datetime to a string produces an ISO 8601 timestamp with a space as the separator and a 6-digit fraction:
str(datetime.datetime(2016, 7, 22, 9, 25, 59, 555555))
# '2016-07-22 09:25:59.555555'
but if the fraction is 0, no fractional part is output.
str(datetime.datetime(2016, 7, 22, 9, 25, 59, 0))
# '2016-07-22 09:25:59'
These two forms need different strptime formats. Since Python 3.7, %z accepts both 2016-07-22 09:25:59+0300 and 2016-07-22 09:25:59+03:00.
There is a single-file library called iso8601 which properly parses ISO 8601 timestamps and only them.
It supports fractions and timezones, and the T separator all with a single function:
import iso8601
iso8601.parse_date('2016-07-22 09:25:59')
# datetime.datetime(2016, 7, 22, 9, 25, 59, tzinfo=<iso8601.Utc>)
iso8601.parse_date('2016-07-22 09:25:59+03:00')
# datetime.datetime(2016, 7, 22, 9, 25, 59, tzinfo=<FixedOffset '+03:00' ...>)
iso8601.parse_date('2016-07-22 09:25:59Z')
# datetime.datetime(2016, 7, 22, 9, 25, 59, tzinfo=<iso8601.Utc>)
iso8601.parse_date('2016-07-22T09:25:59.000111+03:00')
# datetime.datetime(2016, 7, 22, 9, 25, 59, 111, tzinfo=<FixedOffset '+03:00' ...>)
If no timezone is set, iso8601.parse_date defaults to UTC. The default zone can be changed with the default_timezone keyword argument. Notably, if this is None instead of the default, then those timestamps that do not have an explicit timezone are returned as naive datetimes instead:
iso8601.parse_date('2016-07-22T09:25:59', default_timezone=None)
# datetime.datetime(2016, 7, 22, 9, 25, 59)
iso8601.parse_date('2016-07-22T09:25:59Z', default_timezone=None)
# datetime.datetime(2016, 7, 22, 9, 25, 59, tzinfo=<iso8601.Utc>)