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

Given a list of week numbers, how to organize the dates by weekly and split it by the end of month?

I have weekNumList = ['202234', '202235']
where 2022 represents the year and the last 2 digits, 34, represents the week number.

Week 202234 has the end of August and the beginning of September. I’d like to separate it to become like this: [['2022-08-28', '2022-08-29', '2022-08-30', '2022-08-31'], ['2022-09-01', '2022-09-02', '2022-09-03']]

So far, my code only separates it by week:

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

def returnWeeks(year, week):
  days = {'Monday': 1, 'Tuesday': 2, 'Wednesday': 3, 
          'Thursday': 4, 'Friday': 5, 'Saturday': 6, 'Sunday': 7}
  a = datetime.strptime('{0}'.format(year), '%Y') + timedelta(days=7*(week-1))
  a += timedelta(days=7-days.get(a.strftime('%A'), 0))
  for k in range(0, 7):
    yield (a + timedelta(days=k)).strftime('%Y-%m-%d')

days = list(returnWeeks(int(weekNumList[1][:4]), int(weekNumList[1][4:])))
print(days) # ['2022-08-28', '2022-08-29', '2022-08-30', '2022-08-31', '2022-09-01', '2022-09-02', '2022-09-03']

Any ideas how to implement splitting the dates if the week includes the end of month? Thank you!

>Solution :

You could do groupby on your days list.

from datetime import datetime
from itertools import groupby
result = [
        list(l)
        for k, l in groupby(days, key=lambda x: datetime.strptime(x, "%Y-%m-%d").month)
    ]

Output

[['2022-08-28', '2022-08-29', '2022-08-30', '2022-08-31'],
 ['2022-09-01', '2022-09-02', '2022-09-03']]
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