如何在python中获得像我们使用的那样的yearWeek日期时间格式info.InvariantInfo.CalendarC#中的.GetWeekOfYear()?

2024-06-02 08:38:38 发布

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

我想从datetime得到python的yearWeek。我使用了IsoCalender()[1],但它返回的星期与我使用的不同日期时间格式info.InvariantInfo.Calendar.GetWeekOfYear(日期,CalendarWeekRule.FirstDay=第一天, 星期一,星期一). 你知道吗

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.

任何帮助都将受到高度赞扬。你知道吗


Tags: infogetdatetimehave格式时间calendarstrptime
1条回答
网友
1楼 · 发布于 2024-06-02 08:38:38

根据ISO 8601(参见this draft von 2016, section 5.7.7

A week is defined as a seven-day time interval, starting with a Monday. Week number one of the calendar year is the first week that contains at least four (4) days in that calendar year.

Python的date.isocalendar文档同样说明:

[…] week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday.

根据documentation of CalendarWeekRule,这等于CalendarWeekRule.FirstFourDayWeek

Indicates that the first week of the year is the first week with four or more days before the designated first day of the week.

CalendarWeekRule.FirstDay是指:

Indicates that the first week of the year starts on the first day of the year and ends before the following designated first day of the week.

总之,正确的方法是:

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

正确的结果是38。你知道吗

相关问题 更多 >