Reputation: 5488
Given a list containing dates as part of a string:
['2021/08/01/EUR_USD.json',
'2021/08/02/EUR_USD.json',
'2021/08/03/EUR_USD.json',
'2021/08/04/EUR_USD.json',
'2021/08/05/EUR_USD.json',
'2021/08/06/EUR_USD.json',
'2021/08/08/EUR_USD.json',
'2021/08/09/EUR_USD.json',
'2021/08/10/EUR_USD.json',
'2021/08/11/EUR_USD.json',
'2021/08/12/EUR_USD.json',
'2021/08/13/EUR_USD.json',
'2021/08/15/EUR_USD.json']
I want to filter and return only the date and only for Sundays.
This can be done with a list comprehension as follows but I would be interested in other ways of doing this:
def dayOfWeek(l):
subset = ['/'.join(i.split("/")[0:3])
for i in l
if datetime.strptime('/'.join(
i.split("/")[0:3]),'%Y/%m/%d' ).weekday() == 6 ]
return subset
['2021-08-01', '2021-08-08', '2021-08-15']
Upvotes: 1
Views: 294
Reputation: 71451
You can use the calendar
module with an assignment expression for a shorter comprehension:
import calendar as cl, re
l = ['2021/08/01/EUR_USD.json', '2021/08/02/EUR_USD.json', '2021/08/03/EUR_USD.json', '2021/08/04/EUR_USD.json', '2021/08/05/EUR_USD.json', '2021/08/06/EUR_USD.json', '2021/08/08/EUR_USD.json', '2021/08/09/EUR_USD.json', '2021/08/10/EUR_USD.json', '2021/08/11/EUR_USD.json', '2021/08/12/EUR_USD.json', '2021/08/13/EUR_USD.json', '2021/08/15/EUR_USD.json']
r = ['-'.join(d) for i in l if cl.weekday(*map(int, (d:=re.findall('\d+', i)))) == 6]
Output:
['2021-08-01', '2021-08-08', '2021-08-15']
Upvotes: 2
Reputation: 18416
List-comprehension is fine, but another way is to use filter
builtin
list(filter(lambda x:datetime.strptime(x.rsplit('/', 1)[0], '%Y/%m/%d').weekday()==6, l))
['2021/08/01/EUR_USD.json', '2021/08/08/EUR_USD.json', '2021/08/15/EUR_USD.json']
There are other things you can do:
rsplit
, with maxsplit=1
, then take the first item after the split/
delimited date string to -
delimited date string by '-'.join(i.split("/")[0:3]),'%Y-%m-%d' )
which is uselessUpvotes: 2