-1

I have some data that looks like this. I want to add a week_id date column where the week_id represents the Sunday that the week began. I'm super new to python (coming from R) so I would use as.Date with the cut function to do something like this. But all I've seen so far in python documentation is adding like a week number.

customer    date
xxxx    12/1/15
xxxx    12/3/15
xxxx    12/7/15
xxxx    12/13/15
yyyy    12/14/15
yyyy    12/15/15
yyyy    12/21/15

I want the output to look like this

customer    date    week_id
xxxx      12/1/15   11/29/15
xxxx      12/3/15   11/29/15
xxxx      12/7/15   12/6/15
xxxx      12/13/15  12/13/15
yyyy      12/14/15  12/13/15
yyyy      12/15/15  12/13/15
yyyy      12/21/15  12/20/15
Hillary
  • 785
  • 1
  • 6
  • 17
  • This is not difficult, and someone might give you the answer but I think you should start out with some code. One approach is to find the DOW for the current date and then find the previous Sunday. This is easy to do and while your question is not a duplicate of this one - this one should get you started http://stackoverflow.com/questions/9847213/which-day-of-week-given-a-date-python – PyNEwbie Jan 05 '16 at 19:49

1 Answers1

2
from datetime import datetime, timedelta
day = '12/01/15'
date = datetime.strptime(day, '%m/%d/%y')
start_of_week = date - timedelta(days = (date.weekday() + 1) % 7)
print(start_of_week.strftime('%m/%d/%Y'))

11/29/2015

algor
  • 404
  • 2
  • 8