0

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.

3
  • Have you looked in the Calendar module? There's probably something in there to help you find what you need.
    – Atra Azami
    Sep 18, 2013 at 10:21
  • I did calendar.setfirstweekday(0) to set first day of week to Monday, but result didn't change.
    – alwbtc
    Sep 18, 2013 at 10:25
  • Actually, as per ISO calendar definition, the result 1 is correct. See Mathematics of the ISO calendar
    – Rod
    Sep 18, 2013 at 13:59

1 Answer 1

1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.