Comparing date strings in python -


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

i tried compare dates in python3 without using library , seems working correctly. real case? python understands these strings dates , comparing them according date format or else going on behind scenes ?

no, there no spacial thing behind behavior. matter of fact, python compares strings lexicographicaly , in case works, it's not right way go, because can accepts wrong dates!

here counterexample:

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

as proper way dealing dates should use datetime module has lot of tools working date objects.

you can convert strings date object datetime.datetime.strptime , can use basic arithmetic operation compare date objects, they've been supported module.

enter image description here


Comments