我在几个月里做了一个循环,然后得到了第一个星期天(从一个月的1st开始,一直到第二天,直到找到一个星期日为止),然后得到找到日期的年份:from datetime import datetime
from datetime import date
# dayofweek: Sunday=0, Monday=1 and so on
def get_week_number(year=2017, dayofweek=0):
weeks = []
for month in range(1, 13):
# get first Sunday of month
d = date(year, month, 1)
while(d.weekday() != dayofweek):
d = d.replace(day=d.day + 1)
# isocalendar()[1] is the week-of-year field
weeks.append(d.isocalendar()[1])
return weeks
print(get_week_number(2017, 0))
不过,结果与您预期的不同:
^{pr2}$
我也尝试过使用weeks.append(int(d.strftime("%W"))),但得到了相同的结果-我使用的是python3.5.2和a week is defined as:The ISO year consists of 52 or 53 full weeks, and where a 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. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year.