Is it reliable to compare two isoformat datetime strings?

You can compare two ISO strings directly because of two factors:

  1. String comparison algorithm starts from the most left char;
  2. ISO string is formatted in a way that the left char is more significant than right one.

Generally speaking, 'year' is more significant than 'month', the first char of 'year' is more significant than the second char, etc.


ISO 8601 date strings (without timezone offset), which is the type of string returned by isoformat, can be compared as strings.

As Assem-Hafez points out, if the strings include timezone offsets, then string comparison may not produce the same result as timezone-aware datetime comparison:

In [31]: import dateutil.parser as DP

In [32]: s = ["2019-08-29T10:50:35+00:00", "2019-08-29T10:50:35+02:00"]

In [33]: t = [DP.parse(si) for si in s]; t
Out[33]: 
[datetime.datetime(2019, 8, 29, 10, 50, 35, tzinfo=tzutc()),
 datetime.datetime(2019, 8, 29, 10, 50, 35, tzinfo=tzoffset(None, 7200))]

In [34]: s[0] < s[1]
Out[34]: True

In [35]: t[0] < t[1]
Out[35]: False