(Python) PyProgram #6 – Finding weeks of a month

My colleague had a problem, he needed to separate the dates in a month according to weeks. That is, given a month, he has to find the dates in 1st week, dates in 2nd week and so on. This is need to query and collect a weeks data for a given month. He was trying to write his own solution which we Python guys around thought was a bit non-straight forward. My other colleague Jacob sat and wrote a small Py script to order the dates per week of a given month,

from datetime import datetime, timedelta

current_date = datetime.now() year, month = current_date.timetuple()[:2]

first_day_of_month = datetime(year, month, 1)

if month == 12:

    first_day_of_next_month = datetime(year+1, 1, 1)

else:

    first_day_of_next_month = datetime(year, month+1, 1)

#Subtracting 1 day

last_day_of_month = first_day_of_next_month - timedelta(1)

#First and Last days of the month

print first_day_of_month, last_day_of_month

#Computing start and end week days

first_week_day = first_day_of_month.weekday()+1

date_range = [0]*first_week_day + range(first_day_of_month.day,

last_day_of_month.day+1)

month = []

while date_range:

    if len(date_range) >= 7:

        week = date_range[:7]

        date_range = date_range[7:]

    else:

        week = date_range

        date_range = None

     month.append(week)

for week in month:

    print week

for week in month:

    start_week, end_week = min(week), max(week)

    if start_week==0:

        start_week = 1

    print start_week, end_week
Advertisements

2 thoughts on “(Python) PyProgram #6 – Finding weeks of a month

  1. One more way of solving this…

    import calendar
    import time
    y, m = time.localtime(time.time())[:2]
    for i in calendar.month(y, m).split(‘\n’)[2:-1]:
    print i.split()

    Output…
    [‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’]
    [‘7’, ‘8’, ‘9’, ’10’, ’11’, ’12’, ’13’]
    [’14’, ’15’, ’16’, ’17’, ’18’, ’19’, ’20’]
    [’21’, ’22’, ’23’, ’24’, ’25’, ’26’, ’27’]
    [’28’, ’29’, ’30’, ’31’]
    >>>

    • Thank you seShadri for the wonderful code! It so easy to do a lot of things using this method ( n-th day of a specific week, number of days in a week, etc. )

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s