Python确定一年中的一周(非iso方式)

2024-06-02 09:00:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在.NET中有没有一种类似于python的方法?在

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

dt.isocalendar()[1]似乎不适合我,因为它为datetime.date(2010, 1, 1)返回53(预期52)

谢谢。在


Tags: 方法datetimedatenetdtcalendarmondaycultureinfo
1条回答
网友
1楼 · 发布于 2024-06-02 09:00:40

ISO日历有一系列令人困惑的规则,这些规则可能是您在这里面临的问题的根源。特别是,GetWeekOfYear的.NET实现(使用您使用的参数)与ISO非常相似,因此explicit clarifications是必需的,并且从MSDN链接。结果是isocalendar和{}将产生不同的结果[我的重点]:

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.

上面的链接讨论了一些纠正GetWeekOfYear的建议,如果您真的想匹配GetWeekOfYear行为,这两个链接将有帮助,尽管您将对它们的示例应用反向转换。在

最“python”的方法是创建一个函数。这里没有什么特别的地方,除了通常尝试通过做day < 4而不是{}等来最小化代码

(当然,所有这些都是假设Python的isocalendar与ISO日历正确匹配。文档似乎表明它确实存在,其中GetWeekOfYear明确表示它没有,因此这似乎是一个合理的假设。但是,如果这是一个关键的计算,那么无论如何,您将亲自对其进行彻底的测试。)

相关问题 更多 >