Filter a list of students by date of birth using python list comprehension

  • Here we are having a list of 5 students. Each item in this list contain another list which has the id, name and date of birth of the students. The date of birth is a date field which is provided in string format.

    In the below sample we are going to filter all the students who were born in the year 2003. We can easily do this by using python List comprehension.

    Before applying filter on date fields, we have to make sure that these are converted to datetime objects to get the correct results. Then we apply the filter and convert it back to string dates, if needed.
    Refer sample below to know how to do this.

    Copied
    from datetime import datetime
    
    #Id, Name, Date of Birth
    studentsList = [ [1, 'Carl', '2002/10/15'], [2, 'Tim', '2003/01/05'],
        [3, 'Peter', '2002/05/22'], [4, 'George', '2003/7/7'], [5, 'Kim', '2003/3/5'] ]
    
    #String datetime converted to datetime object for filter
    stlistindatetime = [[ st[0], st[1], datetime.strptime(st[2], '%Y/%m/%d') ]  for st in studentsList]
    
    #Students born in 2003
    filteredList = [ st  for st in stlistindatetime if st[2].year == 2003]
    #Convert datetime object to string dates
    stlist = [[ st[0], st[1], datetime.strftime(st[2], '%Y/%m/%d') ]  for st in filteredList]
    
    print(stlist)
    
    Input:
    [
    	[2, 'Tim', '2003/01/05'],
    	[4, 'George', '2003/07/07'],
    	[5, 'Kim', '2003/03/05']
    ]
    
    Output:
    [
    	[1, 'Carl', '2002/10/15'],
    	[2, 'Tim', '2003/01/05'],
    	[3, 'Peter', '2002/05/22'],
    	[4, 'George', '2003/7/7'],
    	[5, 'Kim', '2003/3/5']
    ]
    
  • Dates are in different format

    Above sample has dates in the same format.
    What if the dates of each item are in different format.
    We will have to write another function to do the conversion and call it from the list comprehension.
    Only thing here is that we should know all the expected formats in advance and add it to the formatlist inside the function.

    Copied
    from datetime import datetime
    
    def formatDates(datetoformat):
        formatlist = ['%Y/%m/%d', '%m-%d-%y', '%y.%m.%d', '%m-%d-%Y %H:%M:%S', '%Y.%m.%d %H:%M']
    
        for fl in formatlist:
            try:
                return datetime.strptime(datetoformat, fl)
                break
            except:
                pass
            
        return datetoformat
    
    '12-22-21', '22.01.18', '10-15-2021 08:40:50', '2018.08.14 22:35'
    #Id, Name, Date of Birth
    studentsList = [ [1, 'Carl', '2002/10/15'], [2, 'Tim', '12-22-03'],
        [3, 'Peter', '22.01.03'], [4, 'George', '10-15-2002 08:40:50'], [5, 'Kim', '2003.08.14 22:35'] ]
    
    #String datetime converted to datetime object for filter
    stlistindatetime = [[ st[0], st[1], formatDates(st[2]) ]  for st in studentsList]
    
    #Students born in 2003
    filteredList = [ st  for st in stlistindatetime if st[2].year == 2003]
    #Convert datetime object to string dates
    stlist = [[ st[0], st[1], datetime.strftime(st[2], '%Y/%m/%d') ]  for st in filteredList]
    
    print(stlist)
    
    Input:
    [
    	[1, 'Carl', '2002/10/15'],
    	[2, 'Tim', '12-22-03'],
    	[3, 'Peter', '22.01.03'],
    	[4, 'George', '10-15-2002 08:40:50'],
    	[5, 'Kim', '2003.08.14 22:35']
    ]
    
    Output:
    [
    	[2, 'Tim', '2003/01/05'],
    	[4, 'George', '2003/07/07'],
    	[5, 'Kim', '2003/03/05']
    ]
    
Absolute Code Works - Python Topics