Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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 ?

like image 950
SpiderRico Avatar asked Jul 10 '15 21:07

SpiderRico


People also ask

Can I compare date strings Python?

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. This makes it very easy to compare and check dates for validations, etc.

How do I compare two dates in Python?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1. A result is a timedelta object.

How can I compare two datetime strings?

If both the date/time strings are in ISO 8601 format (YYYY-MM-DD hh:mm:ss) you can compare them with a simple string compare, like this: a = '2019-02-12 15:01:45.145' b = '2019-02-12 15:02:02.022' if a < b: print('Time a comes before b. ') else: print('Time a does not come before b.

Can I use == to compare strings in Python?

Python comparison operators can be used to compare strings in Python. These operators are: equal to ( == ), not equal to ( != ), greater than ( > ), less than ( < ), less than or equal to ( <= ), and greater than or equal to ( >= ).


1 Answers

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.

enter image description here

like image 67
Mazdak Avatar answered Nov 15 '22 08:11

Mazdak