Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it reliable to compare two isoformat datetime strings?

I need to find out which of two isoformatted datetime strings is the latest.

By now, I convert them using datetime.strptime method. Then I compare two datetime objects. Then I call isoformat of the greatest datetime object in order to pass it as a get parameter.

So I'm wondering if it is reliable to find out the greatest isoformatted string without doing converstion from str to datetime.

It seems to work:

>>> from datetime import datetime as dt
>>> s1 = '2013-12-25T19:20:41.391393'
>>> s2 = '2013-12-25T19:20:41.391394'
>>> s1 > s2
False
>>> pattern = '%Y-%m-%dT%H:%M:%S.%f'
>>> dt.strptime(s1, pattern) > dt.strptime(s2, pattern)
False
like image 447
Kzhi Avatar asked Dec 25 '13 15:12

Kzhi


People also ask

Can ISO date strings be compared?

Turning date strings into ISO date stringsYou can't compare just any date string. For instance, "13-Dec-2020" < "20-Apr-2020" alphabetically but not conceptually. But ISO date strings are neatly comparable, for instance, "2020-12-13" > "2020-04-20" both conceptually and alphabetically.

How does Python compare datetime to string?

Python date implementations support all the comparision operators. So, if you are using the datetime module to create and handle date objects, you can simply use the <, >, <=, >=, etc. operators on the dates.


1 Answers

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
like image 124
unutbu Avatar answered Sep 20 '22 15:09

unutbu