datetime 还能判断是星期几。判断星期几有两个方法,一个是isoweekday(),一个是weekday()。前者是,星期几就返回数字几,星期一就返回数字1,星期天就返回数字7。后者是返回的数字减1,比如星期一就返回0,星期天就返回6。个人觉得还是isoweekday()好用些。
import datetime
d = datetime.date(1901,1,1)
delta = datetime.timedelta(1)
res = 0
while d.year < 2001:
if d.isoweekday() == 1:
res += 1
d += delta
print(res) # 5217
或者:
import datetime
start =datetime.datetime(1901,1,1)
end = datetime.datetime(2000,12,31)
res = 0
while start <= end:
if start.isoweekday() == 1:
res += 1
start += datetime.timedelta(days = 1)
print(res)