2

Is there a pythonic way of getting the equivalent of the following in .NET?

CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(dt.Date, CalendarWeekRule.FirstDay, DayOfWeek.Monday)

dt.isocalendar()[1] does not seem to work for me as it returns 53 (expecting 52) for datetime.date(2010, 1, 1)

Thanks.

DerpDerp
  • 307
  • 1
  • 11
  • Decided to take Zooba's advice and wrote a function to mimic the implementation of date.getisocalendar()[1] but for the month, so the first week will be the week with the 4'th or the first week with a Thursday. [link](http://en.wikipedia.org/wiki/ISO_8601) – DerpDerp Feb 08 '11 at 20:34

1 Answers1

3

The ISO calendar has a range of confusing rules that are likely the source of the issues you face here. In particular, the .NET implementation of GetWeekOfYear (with the parameters you have used) is so similar to ISO that explicit clarifications are required and linked from MSDN. The result is that isocalendar and GetWeekOfYear will produce results that differ [my emphasis]:

Specifically ISO 8601 always has 7 day weeks. If the first partial week of a year doesn't contain Thursday, then it is counted as the last week of the previous year. Likewise, if the last week of the previous year doesn't contain Thursday then its treated like the first week of the next year. GetWeekOfYear() has the first behavior, but not the second.

Some suggestions for correcting GetWeekOfYear are discussed at the link above and also at Is .NET giving me the wrong week number for Dec. 29th 2008? If you actually want to match the GetWeekOfYear behaviour these two links will assist, although you will be applying the reverse transformation to their examples.

The most 'Pythonic' way of doing it is to create a function. Nothing particularly special here, except the usual attempt to minimise code by doing things like day < 4 rather than day == 1 or day == 2 ... etc.

(Of course, all of this is assuming that Python's isocalendar correctly matches the ISO calendar. The documentation seems to suggest that it does, where the GetWeekOfYear explicitly states that it doesn't, so it would seem a reasonable assumption. However, if this is a critical calculation, you will be testing it thoroughly yourself anyway.)

Community
  • 1
  • 1
Zooba
  • 11,221
  • 3
  • 37
  • 40
  • That's what I thought. I thought I may have missed something in the calendar documentation. I'll write a function to implement this. – DerpDerp Feb 07 '11 at 00:27