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.
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 thatisocalendarandGetWeekOfYearwill produce results that differ [my emphasis]:Some suggestions for correcting
GetWeekOfYearare 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 theGetWeekOfYearbehaviour 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 < 4rather thanday == 1 or day == 2 ...etc.(Of course, all of this is assuming that Python’s
isocalendarcorrectly matches the ISO calendar. The documentation seems to suggest that it does, where theGetWeekOfYearexplicitly 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.)