How to get week start dates and week number of each week in a year considering start day of the week is Monday in python?

StackOverflow https://stackoverflow.com/questions/18869636

  •  29-06-2022
  •  | 
  •  

Question

How can I get week start dates of each week in a year, considering start day of the week is Monday in python?

This assumes start day is Sunday:

>>>import datetime as datetime

>>>dt = datetime .date(2013,12,30)
>>>dt.isocalendar()[1]
1

However, result shouldn't be 1, because 30-12-2013 is still in 2013.

Was it helpful?

Solution

I don't think behaviour of isocalendar can be changed.

From : http://docs.python.org/2/library/datetime.html#datetime.date.isocalendar

The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday.

But strftime can display week number :

%U "All days in a new year preceding the first Sunday are considered to be in week 0." %W "All days in a new year preceding the first Monday are considered to be in week 0."

>>> import datetime
>>> dt = datetime.date(2013,12,30)
>>> dt.isocalendar()
(2014, 1, 1)
>>> dt.strftime("%U")
'52'

But to respond to your first question, why don't you just use datetime.timedelta ?

>>> import datetime
>>> dt = datetime.date(2013,12,30)
>>> w = datetime.timedelta(weeks=1)
>>> dt - w
datetime.date(2013, 12, 23)
>>> dt + w
datetime.date(2014, 1, 6)
>>> dt + 10 * w
datetime.date(2014, 3, 10)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top