How to find all seven dates of any week in python

I am new to Python (in comparison to my experience in other languages) 🙂 Last month I have done some experiment with python date time calculation. Also one of my project required a function, which will compute all 7 dates of any week of any year in Python.

After some learning (and searching) heres my work :

__author__ = "bahar"
__date__ = "$Sep 23, 2010 4:13:29 PM$"

import datetime
from time import strptime, strftime

def _getWeekDates(_Year = 0, _weekStart = 2, _weekNo = 0):
    """
        Returns a list with all the 7 dates of provided week and year (or any supplied week number)
        _year , example 2010. will be computed, if not provided
        _weekStart, (0 is Saturday, 6 is Friday) to start day of week
        _weekNo, will be computed, if not provided
    """

    now = datetime.datetime.now()
    if _Year = 0:
        _Year = now.year

    if _weekNo = 0:
        _weekNo = datetime.date(now.year,now.month,now.day).isocalendar()[1]
    WeekDates = []
    janOne = strptime('%s-01-01' % _Year, '%Y-%m-%d')

    dayOfFirstWeek = ((7-int((strftime("%u",janOne)))+ int(_weekStart)) % 7)

    if dayOfFirstWeek == 0:
        dayOfFirstWeek = 7
    dateOfFirstWeek = strptime('%s-01-%s' % (_Year, dayOfFirstWeek), '%Y-%m-%d')
    dayOne = datetime.datetime( dateOfFirstWeek.tm_year, dateOfFirstWeek.tm_mon, dateOfFirstWeek.tm_mday )
    daysToGo = 7*(int(_weekNo)-1)
    lastDay = daysToGo+6
    dayX = None
    while daysToGo = lastDay:
        dayX = dayOne + datetime.timedelta(days = daysToGo)
        resultDateX = strptime('%s-%s-%s' % (dayX.year, dayX.month, dayX.day), '%Y-%m-%d')
        WeekDates.append(strftime("%Y-%m-%d", resultDateX))
        daysToGo += 1
    return WeekDates

if __name__ == '__main__':
        now = datetime.datetime.now()
        weekNo = datetime.date(now.year,now.month,now.day).isocalendar()[1]

        WeekData = _getWeekDates()
        days = ['Monday', 'Tuesday', 'Wedensday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
        result = dict(zip(days, WeekData))

        for day in days:
            print day ,':', result[day]

Output:

Monday : 2010-10-18
Tuesday : 2010-10-19
Wedensday : 2010-10-20
Thursday : 2010-10-21
Friday : 2010-10-22
Saturday : 2010-10-23
Sunday : 2010-10-24

For Python date time related functions/modules, I find this site useful: http://www.tutorialspoint.com/python/python_date_time.htm

Any suggestion/advice via comments are welcome 🙂

  • Lazarof

    http://askbahar.com/2010/10/23/find-all-seven-dates-of-week-in-python/

    from datetime import date, timedelta

    def get_week_days(year, week):
    d = date(year,1,1)
    if(d.weekday()>3):
    d = d+timedelta(7-d.weekday())
    else:
    d = d – timedelta(d.weekday())
    dlt = timedelta(days = (week-1)*7)
    return d + dlt, d + dlt + timedelta(days=6)

  • Your solution to find first and last date of a week seems easier and clean 🙂

    Thanks for the suggestion.