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() 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() 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-18Tuesday : 2010-10-19Wedensday : 2010-10-20Thursday : 2010-10-21Friday : 2010-10-22Saturday : 2010-10-23Sunday : 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 🙂