I need Calculate dates for week in python
I need this
year = 2012
week = 23
(a,b) = func (year,week)
print a
print b
>>>2012-04-06
>>>2012-06-10
Could you help me ?
I need Calculate dates for week in python
I need this
year = 2012
week = 23
(a,b) = func (year,week)
print a
print b
>>>2012-04-06
>>>2012-06-10
Could you help me ?
The date object contains a weekday()
method.
This returns 0 for monday 6 for sunday.
(From googling) here is one solution: http://www.protocolostomy.com/2010/07/06/python-date-manipulation/ )
I think this can be made a little less verbose so here's my stab at it:
def week_magic(day):
day_of_week = day.weekday()
to_beginning_of_week = datetime.timedelta(days=day_of_week)
beginning_of_week = day - to_beginning_of_week
to_end_of_week = datetime.timedelta(days=6 - day_of_week)
end_of_week = day + to_end_of_week
return (beginning_of_week, end_of_week)
Little outdated answer, but there is a nice module called isoweek that really gets the trick done. To answer the original question you could do something like:
from isoweek import Week
week = Week(2012, 23)
print(week.monday())
print(week.sunday())
Hope this helps anybody.
I think @Anthony Sottile's answer should be this:
def week_magic(day):
day_of_week = day.weekday()
to_beginning_of_week = datetime.timedelta(days=day_of_week)
beginning_of_week = day - to_beginning_of_week
to_end_of_week = datetime.timedelta(days=6 - day_of_week)
end_of_week = day + to_end_of_week
return (beginning_of_week, end_of_week)
It works!
I think the answer he is looking for is in datetime.isocalendar(datetime) It returns a 3-tuple containing ISO year, week number, and weekday.
From any particular year (i.e '2015') one can determine the first day of the first week and then from there keep adding days using the timedelta function to find the particular week requested. With this information one can then return the first and last day of that week.