2

Does Python automatically scan for data types and take a best guess in some cases? In pandas I can understand why one date is bigger than another(because it's set as a date time index), for example in this case:

        DT
2016-05-20 22:22:00
2016-05-20 22:22:01

But in Python:

dt1 = '2016-05-20 22:22:00'
dt2 = '2016-05-20 22:22:01'
if dt2 > dt1:
    print dt2
>>'2016-05-20 22:22:01'

So am I right to assume Python is automatically recognizing these as dates, or is there just some kind of fluke comparison of strings going on? Hence, is it safe to do this?

EDIT This question might differ from the proposed duplicate answer "String Comparison Technique Used by Python" as it uses dates, times and colons. The proposed duplicate answer gives some theoretical insight into lexicographical ordering, with groups of letters used in the examples, and while it may well be complete, there may sill be some uncertainty as to whether comparing sting dates is fail safe.

Hence for anyone stumbling across this: YES, you can compare string dates, safely.

ajsp
  • 2,512
  • 22
  • 34
  • 2
    Possible duplicate of [String Comparison Technique Used by Python](http://stackoverflow.com/questions/4806911/string-comparison-technique-used-by-python) – Łukasz Rogalski May 24 '16 at 21:31

1 Answers1

1

Python strings are compared using "lexicographical order", i.e. Python checks the first char to see what string is bigger... if the two first chars are equal then Python goes for the second char and so on until there is one different char of one of the two string finishes.

So for dates with format YYYY:MM:DD hh:mm:ss the comparison will also be correct in time ordering sense.

6502
  • 112,025
  • 15
  • 165
  • 265
  • Could you please help me to understand why '2019/09/01' < '2019/10/02' is True? On the month part, lexicographically, '0' < '1' - True. But then shouldn't '9' < '0' be False and turn all comparison to False?? – Vladimir Kolenov Aug 07 '19 at 09:10