-1

There is a list of dates in the form of array list Example : 11/02/2012 21/04/2019 12/03/2061 11/09/1961 22/08/2014

We will have to return the third latest date from the above list

I feel we will have to first sort in descending order of year and take the third latest date from that

Could you please give me a suggestions on this?

Vibhutha Kumarage
  • 1,372
  • 13
  • 26
mouli rv
  • 9
  • 2

4 Answers4

3

Is this the way you expect

>>> import datetime
>>> list = ['11/02/2012', '21/04/2019', '12/03/2061', '11/09/1961', '22/08/2014']
>>> d_list = [ datetime.datetime.strptime(d,'%d/%m/%Y') for d in list]
>>> d_list
[datetime.datetime(2012, 2, 11, 0, 0), datetime.datetime(2019, 4, 21, 0, 0), datetime.datetime(2061, 3, 12, 0, 0), datetime.datetime(1961, 9, 11, 0, 0), datetime.datetime(2014, 8, 22, 0, 0)]
>>> sorted(d_list)
[datetime.datetime(1961, 9, 11, 0, 0),
 datetime.datetime(2012, 2, 11, 0, 0),
 datetime.datetime(2014, 8, 22, 0, 0),
 datetime.datetime(2019, 4, 21, 0, 0),
 datetime.datetime(2061, 3, 12, 0, 0)]
darksky
  • 1,955
  • 16
  • 28
Vibhutha Kumarage
  • 1,372
  • 13
  • 26
1

Assuming that you have datetime object in a list:

l = [list containing datetime objects]
l.sort()
l[2]

Should give you third latest date

Rahul
  • 10,830
  • 4
  • 53
  • 88
0

Without using the built in libraries, one way to do this is to:

  1. Get the year, month, and date into a tuple. For instance, "11/02/2012" can be represented as (2012, 02, 11).
  2. Run sort.
  3. Retrieve the third latest date on the sorted list using sorted_dates[-3].

We can get the year, month, and date in the following way:

(d, m, y) = "11/02/2012".split('/')

Then, simply reverse the tuple, and run sort.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
0

So before working on dates you actually have to convert it into actual datetime object so simply do this:

from datetime import datetime


lst = ['11/02/2012' ,'21/04/2019' , '12/03/2061' , '11/09/1961' , '22/08/2014']
lstnew = []
for x in lst:
    lstnew.append(datetime.strptime(x, '%d/%m/%Y'))

now you can run the sort or find the max

for sorting the list use sorted(lstnew) for max use max(lstnew)

Bhawesh Chandola
  • 511
  • 5
  • 19