Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Monday and Sunday based on the given daterange

Tags:

python

Is it possible to get all Mondays & Sundays and store it in a nested list / tuple.

Sample data:
dates = [2010-01-01, 2010-01-04, 2010-01-05, 2010-01-06, 2010-01-08, 2010-01-10, 2010-01-11, 2010-01-15, 2010-01-17]

Expected result:
result = ([2010-01-04, 2010-01-10], [2010-01-11, 2010-01-17])

To clarify the expected result, I want to group result with ([Monday, Sunday], [Monday, Sunday]).

like image 610
jd_py Avatar asked Dec 14 '22 10:12

jd_py


1 Answers

from datetime import datetime

dates = ['2010-01-01', '2010-01-04', '2010-01-05', '2010-01-06',
         '2010-01-08', '2010-01-10', '2010-01-11', '2010-01-15',
         '2010-01-17']

def weekday(date_str):
    return datetime.strptime(date_str, '%Y-%m-%d').weekday()

result = [[date for date in dates if weekday(date) == n] for n in {6, 0}]

print(result)
>>> [['2010-01-04', '2010-01-11'], ['2010-01-10', '2010-01-17']]
like image 185
Simon Fromme Avatar answered Dec 26 '22 13:12

Simon Fromme