python 2.7 how to read in dates

54 Views Asked by At

I have a python 2.7 question

My data has the format below. (it is stock market data) The data name is finallist and it is a list in python.

[['AGGP', '15-Mar-18', '19.22', '19.25', '19.2', '19.23', '26800\n'],
 ['AGGY', '15-Mar-18', '49.17', '49.18', '49.09', '49.16', '42500\n'],
 ['AGQ', '15-Mar-18', '31.6', '31.605', '31.27', '31.3', '112900\n'],
 ['AGT', '15-Mar-18', '31.83', '31.83', '31.81', '31.81', '2600\n'],
 ['AADR', '6-Mar-18', '60.4', '60.58', '60.17', '60.4', '18200\n'],
 ['AAMC', '6-Mar-18', '65.2', '65.2', '65.2', '65.2', '100\n'],    
 ['AAU', '6-Mar-18', '0.89', '0.9', '0.86', '0.87', '147500\n'],
 ['ABE', '6-Mar-18', '15.17', '15.29', '15.12', '15.2', '13700\n']]

I am trying to sort by the 2nd column of the list but making sure the program understands the values is a date.

I have tried the following and it does not work.

import datetime import time finallist.sort(key=lambda finallist: datetime.strptime(finallist[0][0][1] , '%d-%b-%y'))

It Should sort the list by the dates reading each date as a date but it does not. Could anyone offer any thoughts on how to do this? Apologies if this is repeated but I looked at several other examples on line but none seemed to work or match my situation.

Thanks in advance.

2

There are 2 best solutions below

1
On

You'll basically just want

import datetime
finallist.sort(key=lambda row: datetime.datetime.strptime(row[1], '%d-%b-%y'))

but another approach, which is useful if you need to further process the data, is to preprocess the datetimes first:

import datetime

data = [
    ["AGGP", "15-Mar-18", "19.22", "19.25", "19.2", "19.23", "26800\n"],
    ["AGGY", "15-Mar-18", "49.17", "49.18", "49.09", "49.16", "42500\n"],
    ["AGQ", "15-Mar-18", "31.6", "31.605", "31.27", "31.3", "112900\n"],
    ["AGT", "15-Mar-18", "31.83", "31.83", "31.81", "31.81", "2600\n"],
    ["AADR", "6-Mar-18", "60.4", "60.58", "60.17", "60.4", "18200\n"],
    ["AAMC", "6-Mar-18", "65.2", "65.2", "65.2", "65.2", "100\n"],
    ["AAU", "6-Mar-18", "0.89", "0.9", "0.86", "0.87", "147500\n"],
    ["ABE", "6-Mar-18", "15.17", "15.29", "15.12", "15.2", "13700\n"],
]

for datum in data:
    datum[1] = datetime.datetime.strptime(datum[1], "%d-%b-%y")

data.sort(key=lambda datum: datum[1])
0
On

It should look like this:

from datetime import datetime

sorted(finallist, key=lambda x: datetime.strptime(x[1], '%d-%b-%y'))

#[['AADR', '6-Mar-18', '60.4', '60.58', '60.17', '60.4', '18200\n'],
# ['AAMC', '6-Mar-18', '65.2', '65.2', '65.2', '65.2', '100\n'],
# ['AAU', '6-Mar-18', '0.89', '0.9', '0.86', '0.87', '147500\n'],
# ['ABE', '6-Mar-18', '15.17', '15.29', '15.12', '15.2', '13700\n'],
# ['AGGP', '15-Mar-18', '19.22', '19.25', '19.2', '19.23', '26800\n'],
# ['AGGY', '15-Mar-18', '49.17', '49.18', '49.09', '49.16', '42500\n'],
# ['AGQ', '15-Mar-18', '31.6', '31.605', '31.27', '31.3', '112900\n'],
# ['AGT', '15-Mar-18', '31.83', '31.83', '31.81', '31.81', '2600\n']]