
在最近的需求开发中,涉及到使用Python获取当前周指定星期的具体日期,特此记录总结下来,方便日后学习复盘
from datetime import datetime
from datetime import timedelta
def get_current_week_day(week_day="monday"):
'''
作用: 获取当前周指定星期的具体日期
参数:
week_day:星期(str格式)
week_day的值是["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]之一
默认值为"monday"
返回结果: 年月日格式的字符串类型数值
示例: Monday = get_current_week_day("monday")
'''
today = datetime.now()
# datetime模块中,星期一到星期天对应数字0到6
week_days = dict(zip(("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"), range(7)))
delta_hour = timedelta(days=1) # 改变幅度为1天
while today.weekday() != week_days.get(week_day):
if today.weekday() > week_days.get(week_day):
today -= delta_hour
elif today.weekday() < week_days.get(week_day):
today += delta_hour
else:
pass
return today.strftime("%Y%m%d")
用于调用上述函数的具体日期为2022/10/20,该天是星期四
Monday = get_current_week_day("monday") # "20221017"
Tuesday = get_current_week_day("tuesday") # "20221018"
Wednesday = get_current_week_day("wednesday") # "20221019"
Thursday = get_current_week_day("thursday") # "20221020"
Friday = get_current_week_day("friday") # "20221021"
Saturday = get_current_week_day("saturday") # "20221022"
Sunday = get_current_week_day("sunday") # "20221023"