Comparing date strings in python

>> a ='2009-05-10'
>>> b ='2009-06-10'
>>> a > b
False
>>> a < b
True
>>> type(a)
<class 'str'>
>>> c = '2009-06-09'
>>> b < c
False
>>> b > c
True
>>> c ='2008-07'
>>> b > c
True
>>> a > c
True

I tried comparing dates in python3 without using a library and it seems to work correctly. Is this a real case? Does python really understand that these strings are dates and compare them according to the date format, or is something else going on behind the scenes?

+4
source share
1 answer

No, there is no spatial thing behind this behavior. In fact, Python compares lexicographicaly strings, in which case it works, but this is not the right way, because it can also accept incorrect dates!

Here is a Counterexample :

>>> a ='2009-33-10'
>>> b ='2009-11-1'
>>> a>b
True

datetime , .

datetime.datetime.strptime, , ' .

enter image description here

+7

All Articles