Rakesh
Rakesh

Reputation: 13

Trying to find latest date in an array using max but getting different results

I am trying to find latest date in an array using python max but im getting different results

The expected result for this is fine

>>> a = ["10-09-1988","20-10-1999"]
>>> max(a)
'20-10-1999'

Since 20-10-1999 is latest date

But for this one

>>> a = ["10-10-1999","20-10-1988"]
>>> max(a)
'20-10-1988'

The expected output is

10-10-1999

Since 10-10-1999 is latest date but im getting 20-10-1988

How get latest date in array on elements in python (date format is dd-mm-yyy)

for the above one i want (10-10-1999) as output

Upvotes: 1

Views: 2052

Answers (3)

McGrady
McGrady

Reputation: 11477

You can convert string to datetime object, or maybe this following code can do this:

>>> a = ["10-09-1988","20-02-1989","20-09-1988"]
>>> max(a,key=lambda x:(x[6:10],x[3:5],x[:2]))
'20-02-1989'

It is more efficient than convert string to datetime object:

>>> import timeit
>>> s = """
... a=['28-07-2002', '12-02-1976', '23-10-1967', '27-04-1913', '05-06-1901', '06-12-1964', '04-12-1982', '03-04-1929', '07-02-1943', '03-08-1955']
... import datetime
... max(a, key=lambda x: datetime.datetime.strptime(x, "%d-%m-%Y"))
... """
>>> timeit.timeit(stmt=s,number=10000)
1.0200450420379639
>>> s = """
... a=['28-07-2002', '12-02-1976', '23-10-1967', '27-04-1913', '05-06-1901', '06-12-1964', '04-12-1982', '03-04-1929', '07-02-1943', '03-08-1955']
... import datetime
... max(a,key=lambda x:(x[6:10],x[3:5],x[:2]))
... """
>>> timeit.timeit(stmt=s,number=10000)
0.04339408874511719

Upvotes: 1

Charul
Charul

Reputation: 450

In order to compare them, you need to convert the date represented as string to datetime object.

>>> from datetime import datetime
>>> a = ["10-10-1999","20-10-1988"]
>>> for i, date in enumerate(a):
...     a[i] = datetime.strptime(a[i], "%d-%m-%Y")
...
>>> a
[datetime.datetime(1999, 10, 10, 0, 0), datetime.datetime(1988, 10, 20, 0, 0)]
>>> max(a)
datetime.datetime(1999, 10, 10, 0, 0)

Upvotes: 1

Hackaholic
Hackaholic

Reputation: 19733

you need to use key to convert the string to datetime object:

>>> import datetime
>>> a = ["10-09-1988","20-10-1999"]
>>> max(a, key=lambda x: datetime.datetime.strptime(x, "%d-%m-%Y"))
'20-10-1999'

Upvotes: 3

Related Questions