Extract all occurrences of timestamp in string
Question:
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:
['21042022', '1', '21052022', '2', '21062022', '3']
I don’t want the 1
, 2
and 3
.
Please help
Answers:
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)]
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:
['21042022', '1', '21052022', '2', '21062022', '3']
I don’t want the 1
, 2
and 3
.
Please help
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)]