首页 > 解决方案 > How to get yearWeek in python like we get using DateTimeFormatInfo.InvariantInfo.Calendar.GetWeekOfYear() in C#?

问题描述

I want to get yearWeek in python from datetime. I have used IsoCalender()[1] but it returns different week then I get in C# using DateTimeFormatInfo.InvariantInfo.Calendar.GetWeekOfYear(Date, CalendarWeekRule.FirstDay, DayOfWeek.Monday).

I have tried:

1) IsoCalender()[1].

2) d = datetime.datetime.strptime('2017-09-22 00:00:00.00','%Y-%m-%d %H:%M:%S.%f')
print(datetime.datetime.strftime(d,'%W'))

So For '2017-09-22 00:00:00.00' In C# I get 39 but I get 38 in python using above mentioned techniques.

Any help will be highly appretiated.

标签: c#python

解决方案


根据 ISO 8601(参见此草案 von 2016,第 5.7.7 节

一周被定义为从星期一开始的 7 天时间间隔。日历年的第一周是该日历年中包含至少四 (4) 天的第一周。

Python 的date.isocalendar的文档同样指出:

[…] 一周从星期一开始,到星期日结束。ISO 年的第一周是包含星期四的一年中的第一个(公历)日历周。

根据CalendarWeekRule 的文档,这等于CalendarWeekRule.FirstFourDayWeek

表示一年中的第一周是在指定的一周的第一天之前四天或更多天的第一周。

鉴于CalendarWeekRule.FirstDay

表示一年的第一周从一年的第一天开始,在下一个指定的一周的第一天之前结束。

总之,C#中的正确方法是:

DateTimeFormatInfo.InvariantInfo.Calendar.GetWeekOfYear(new DateTime(2017, 9, 22), CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)

正确产生 38。


推荐阅读