1

I have a list that contains dictionaries(my_list) that looks like

[{'name': 'jane', 'number': 123, 'birthday': '04/05/78'}, 
 {'name': 'summer', 'number': 542, 'birthday': '07/01/1990'},
 {'name': 'carter', 'number': 003, 'birthday': '12/15/1992'}]

I am trying to filter out results by a birthday

my_filter = [elf for elf in my_list if 'birthday' >= '01/01/1980']

This should eliminate the first entry but when i print out my filter all three entries are still being printed.

How can i compare the string dates (birthday) to filter out data?

0

1 Answer 1

2

You can use datetime.strptime to parse the date strings into datetime objects for comparison. Since the year portions of your date strings are inconsistently formatted, you should normalize them first with a regex substitution:

from datetime import datetime
import re
my_list = [{'name': 'jane', 'number': 123, 'birthday': '04/05/78'},
 {'name': 'summer', 'number': 542, 'birthday': '07/01/1990'},
 {'name': 'carter', 'number': 3, 'birthday': '12/15/1992'}]
print([elf for elf in my_list if datetime.strptime(re.sub(r'\d\d(\d\d)$', r'\1', elf['birthday']), '%m/%d/%y') >= datetime(1980, 1, 1)])

This outputs:

[{'name': 'summer', 'number': 542, 'birthday': '07/01/1990'}, {'name': 'carter', 'number': 3, 'birthday': '12/15/1992'}]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.