Skip to content

Instantly share code, notes, and snippets.

@shanehh
Created July 24, 2021 11:43
Show Gist options
  • Save shanehh/b1a368510f31c3468d18c29c25d0545a to your computer and use it in GitHub Desktop.
Save shanehh/b1a368510f31c3468d18c29c25d0545a to your computer and use it in GitHub Desktop.
python datetime package 有提供符合 iso 8601 标准的 date.isoweekday. 此 snippet 的代码根据 date 算出 weeknum,像是 excel 里 WEEEKNUM 的默认行为:即不论如何,1/1 日是第一周,sunday 作为一周的第一天
import datetime as dt
def weeknum(date):
# 如果新年的第一天就是星期天的话
# 直接通过天数的差异算 weeknum
# 规则是:
# 1. 每满 7 天,周数加 1
# 2. 如果有余数,或余数就为 0(本身是 sunady 的情况)也加 1
# 最终数学公式就是:floor division 7, plus 1
first_day = dt.date(date.year, 1, 1)
if first_day.strftime("%A") == "Sunday":
return (date - first_day).days // 7 + 1
# 否则新年的第一个星期天
# 是第二周的第一天
w2d1 = None
for i in range(1, 8):
d = dt.date(date.year, 1, i)
if d.strftime("%A") == "Sunday":
w2d1 = d
break
if date < w2d1:
return 1
return (date - w2d1).days // 7 + 2
if __name__ == "__main__":
for y in range(1900, 2999):
d = dt.date(y, 1, 1)
if d.strftime("%A") == "Sunday":
print("first day is sunday", d)
break
print(weeknum(dt.date(2021, 1, 1)))
print(weeknum(dt.date(2005, 1, 2)))
print(weeknum(dt.date(1905, 1, 2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment