3

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 ?

Jonatan Wagner
  • 85
  • 1
  • 1
  • 2

4 Answers4

13

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)
anthony sottile
  • 61,815
  • 15
  • 148
  • 207
  • this is not in python but result is same for i in `seq 0 52`; do echo "SELECT date('now', 'localtime', 'start of year', '$(($i * 7)) days') AS ws, date('now', 'localtime', 'start of year', '$(($i * 7 + 7)) days') AS we;";done | sqlite3 this will generate list of week limits for SQL and in second pass I will use it for sumarize in second SQL SELECT how I may send NEWLINE here????? enter is not working as ussual – Jonatan Wagner Jun 06 '12 at 15:37
  • week 1 2012-01-01 to 2012-01-07 week 2 2012-01-08 to 2012-01-14 week 3 2012-01-15 to 2012-01-21 week 4 2012-01-22 to 2012-01-28 week 5 2012-01-29 to 2012-02-04 week 6 2012-02-05 to 2012-02-11 week 7 2012-02-12 to 2012-02-18 week 8 2012-02-19 to 2012-02-25 week 9 2012-02-26 to 2012-03-03 – Jonatan Wagner Jun 06 '12 at 18:07
5

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.

Lino Bossio
  • 103
  • 1
  • 8
4

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!

LeoShi
  • 1,637
  • 2
  • 14
  • 24
1

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.

cigarman61
  • 11
  • 1