4

Total newbie to Python, so apologies in advance if this is obvious. I have a number of datetime values, for which I would like to identify a year and week number, for example:

start_date = datetime.datetime(2015,1,26,0,0,0)

The catch is, I would like the week to be defined as starting on a Sunday.

I understand that the datetime.isocalendar() can get me week numbers, but they will be calculated under the assumption that weeks start on Mondays. Is there any other way?

Edit: Running Python 2.7.6

Thank you!

SoHei
  • 274
  • 1
  • 4
  • 10
  • possible duplicate of [How to determine the first day of week in python](http://stackoverflow.com/questions/4265697/how-to-determine-the-first-day-of-week-in-python) – Nir Alfasi Feb 03 '15 at 17:28
  • To be clear, I'm not trying to figure out the first day of the week, I'm trying to figure out the week number. Those are two very different problems. – SoHei Feb 03 '15 at 17:34
  • 1
    What have you tried? Which version of python? Have you looked at `date.isocalendar`. I called up the docs for datetime and searched for 'week number' – kdopen Feb 03 '15 at 17:41
  • Yes, @kdopen: as I explained above, isocalendar defines weeks as starting with Mondays, not Sundays. I need the week to be defined as running Sunday through end of Saturday. – SoHei Feb 03 '15 at 17:45

2 Answers2

16

String format %U will give the week of the year counting from Sunday:

t1 = datetime.datetime.now()
t1.strftime("%U")

See http://strftime.org/ for full list of format parameters.

jlb83
  • 1,988
  • 1
  • 19
  • 30
  • unfortunately this method isn't link with iso standard, eg. pd.to_datetime('2021-01-01').week, int(pd.to_datetime('2021-01-01').strftime("%U")) In years where is 53. week it return 0 for first week not 1 – tararuj4 Apr 07 '23 at 11:39
0

you can just do +1 to the date you're working with and the isocalendar()[1] will work :)

Enric
  • 1