Reputation: 1923
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
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