gwydion93
gwydion93

Reputation: 1923

Getting the max date from a list of date strings

I have a list of dates as strings:

dates = ['12/24/2017','7/7/2011','3/5/2016', '4/21/2018']

I want to get the most current date. However, I can't just use max() for this list.

max(dates)
>>> `7/7/2011'

Is there a simpler way (mod or library)?

Upvotes: 1

Views: 7341

Answers (1)

AChampion
AChampion

Reputation: 30258

You can use max() but you have to use the key param to convert the date string to true dates so they compare correctly, e.g.:

In []:
from datetime import datetime
max(dates, key=lambda d: datetime.strptime(d, '%m/%d/%Y'))

Out[]:
'4/21/2018'

You could convert them all true dates and then just call max():

In []:
dates = [datetime.strptime(d, '%m/%d/%Y') for d in dates]
max(dates)

Out[]:
datetime.datetime(2018, 4, 21, 0, 0)

Upvotes: 4

Related Questions