我正在写一个程序来帮助管理我的梦幻足球联赛。作为其中的一部分,我需要确定我们处于哪一周的比赛中。对于那些不熟悉的人来说,梦幻足球周与标准周不同,每个梦幻周从周二开始,到下周一结束。
我是Python的新手,我已经编写了完成我想做的事情的代码,但我相信有更好的方法。我很好奇未来会有什么更好的方法来解决这个问题。特别是,我不希望每一季都要改变这些变量。
import datetime
timenow = datetime.datetime.now().date()
week1start = datetime.date(day=9, month=9, year=2021)
week1end = datetime.date(day=13, month=9, year=2021)
week2start = datetime.date(day=14, month=9, year=2021)
week2end = datetime.date(day=20, month=9, year=2021)
week3start = datetime.date(day=21, month=9, year=2021)
week3end = datetime.date(day=27, month=9, year=2021)
week4start = datetime.date(day=28, month=9, year=2021)
week4end = datetime.date(day=4, month=10, year=2021)
week5start = datetime.date(day=5, month=10, year=2021)
week5end = datetime.date(day=11, month=10, year=2021)
week6start = datetime.date(day=12, month=10, year=2021)
week6end = datetime.date(day=18, month=10, year=2021)
week7start = datetime.date(day=19, month=10, year=2021)
week7end = datetime.date(day=25, month=10, year=2021)
week8start = datetime.date(day=26, month=10, year=2021)
week8end = datetime.date(day=1, month=11, year=2021)
week9start = datetime.date(day=2, month=11, year=2021)
week9end = datetime.date(day=8, month=11, year=2021)
week10start = datetime.date(day=9, month=11, year=2021)
week10end = datetime.date(day=15, month=11, year=2021)
week11start = datetime.date(day=16, month=11, year=2021)
week11end = datetime.date(day=22, month=11, year=2021)
week12start = datetime.date(day=23, month=11, year=2021)
week12end = datetime.date(day=29, month=11, year=2021)
week13start = datetime.date(day=30, month=11, year=2021)
week13end = datetime.date(day=6, month=12, year=2021)
week14start = datetime.date(day=7, month=12, year=2021)
week14end = datetime.date(day=13, month=12, year=2021)
week15start = datetime.date(day=14, month=12, year=2021)
week15end = datetime.date(day=20, month=12, year=2021)
week16start = datetime.date(day=21, month=12, year=2021)
week16end = datetime.date(day=27, month=12, year=2021)
def get_current_week():
if timenow < week1start:
return 0
elif week1start <= timenow <= week1end:
return 1
elif week2start <= timenow <= week2end:
return 2
elif week3start <= timenow <= week3end:
return 3
elif week4start <= timenow <= week4end:
return 4
elif week5start <= timenow <= week5end:
return 5
elif week6start <= timenow <= week6end:
return 6
elif week7start <= timenow <= week7end:
return 7
elif week8start <= timenow <= week8end:
return 8
elif week9start <= timenow <= week9end:
return 9
elif week10start <= timenow <= week10end:
return 10
elif week11start <= timenow <= week11end:
return 11
elif week12start <= timenow <= week12end:
return 12
elif week13start <= timenow <= week13end:
return 13
elif week14start <= timenow <= week14end:
return 14
elif week15start <= timenow <= week15end:
return 15
elif week16start <= timenow <= week16end:
return 16
使用楼层划分的简单解决方案:
start = datetime.date(day=7, month=9, year=2021)
timenow = datetime.date.today()
week = (timenow - start).days // 7 + 1