Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter out strings from a list of strings with dates?

How to filter out this list, so that we are left with only a list of strings that are in yyyy-mm-dd format?

2021-11-11
2021-10-01
some_folder
some_other_folder

so that we end up with a list like so:

2021-11-11
2021-10-01

Also what if the list has a prefix?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

root/2021-11-11
root/2021-10-01
user/some_folder
root/some_other_folder

and we wanted to end up with:

root/2021-11-11
root/2021-10-01

>Solution :

I would let datetime module handle that for me using strptime. If it is not in '%Y-%m-%d' format, it raises ValueError :

import datetime

lst = ['2021-11-11', '2021-10-01', 'some_folder', 'some_other_folder',
       'root/2021-11-11', 'root/2021-10-01',
       'user/some_folder', 'root/some_other_folder']


def filter(s):
    last_part = s.rsplit('/', maxsplit=1)[-1]
    try:
        datetime.datetime.strptime(last_part, '%Y-%m-%d')
        return True
    except ValueError:
        return False


print([i for i in lst if filter(i)])

output :

['2021-11-11', '2021-10-01', 'root/2021-11-11', 'root/2021-10-01']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading