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

Extract all occurrences of timestamp in string

I have a string like this in Python:

string = "21042022_item1_21052022_item2_21062022_item3" 

How can I extract the dates from this string in a list?
Here’s my code:

import re

s = "21042022_item1_21052022_item2_21062022_item3"

print(re.findall('\d+',s))

but the result is not what I’m after:

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

['21042022', '1', '21052022', '2', '21062022', '3']

I don’t want the 1, 2 and 3.
Please help

>Solution :

This is a simple case, so technically it could be achievable without the re module also:

>>> string = "21042022_item1_21052022_item2_21062022_item3" 
>>> [x for x in string.split('_') if x.isnumeric()]
['21042022', '21052022', '21062022']

In case you’d like to work with date objects instead of str:

>>> from datetime import datetime
>>> [datetime.strptime(x, '%d%m%Y').date() for x in string.split('_') if x.isnumeric()]
[datetime.date(2022, 4, 21), datetime.date(2022, 5, 21), datetime.date(2022, 6, 21)]
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