Comparing date strings in python
No, there is no spacial thing behind this behavior. As a matter of fact, Python compares the strings lexicographicaly and in this case it works, but it's not the right way to go, because it can also accepts the wrong dates!
Here is a Counterexample:
>>> a ='2009-33-10'
>>> b ='2009-11-1'
>>> a>b
True
As a proper way for dealing with dates you should use datetime
module which has a lot of tools for working with date objects.
You can convert your strings to date object with datetime.datetime.strptime
and then you can use basic arithmetic operation to compare your date objects, as they've been supported already by this module.
Related videos on Youtube
SpiderRico
I once had an unicorn who disliked to eat coconuts on sunny weathers.
Updated on September 15, 2022Comments
-
SpiderRico over 1 year
>> 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 to compare dates in python3 without using a library and it seems to be working correctly. Is this the real case? Does python really understands that these strings are dates and comparing them according to date format or is something else is going on behind the scenes ?
-
jonrsharpe almost 9 yearsIf you pick a sensible date format like that, the standard lexicographical sorting of strings works as if it knew they were dates; it doesn't, though.
-
dawg almost 9 yearsThat is why ISO 8601 has
YYYYMMDD
and lets lexicographical sorting take care of the rest. The dates are not parsed or validated.
-
-
Devy almost 7 years@Kasramvd there is no problem with your explanation. However, is the context of when datetime strings are uniformly formatted (so that your example doesn't apply) and were formatted directed from the datetime objects, then the direct datetime string comparison is actually a nice perk of Python3!
-
Mazdak almost 7 years@Devy Indeed, in that case you can. But, basically you better to not do that (cause generally it's not guaranteed to always receive a consistent format) unless it can gives you a significant change in performance.