
#!/usr/bin/env python
# -*- coding = utf-8 -*-
# @Time : 2021/3/30 20:55
# @Author : 陈良兴
# @File : test_week
# @Software : PyCharm
import datetime
from calendar import *
def date_conversation(year, week):
'''
已知年份和周数,获取第N周的周一对应的日期
:param year: 年份
:param week: 周数
:return:第n周周一对应的日期
'''
# 输入的字符串类型的年和日转换为整型
day = int((int(week) - 1) * 7 + 1)
year = int(year)
# first_day:此年的第一天
first_day = datetime.datetime(year, 1, 1) # 2021-01-01 00:00:00
# 判断每年的第一周周一
first_day_text = str(first_day)
lis = ['1', '2', '3', '4', '5', '6', '7']
y = first_day_text[0:4]
m = first_day_text[5:7]
d = first_day_text[8:10]
dic = dict(enumerate(lis))
# 每年第一天是周几
if y.isdigit() and m.isdigit() and d.isdigit() and 1 <= int(m) <= 12 and 1 <= int(d) <= 31:
w = dic[weekday(int(y), int(m), int(d))]
if int(w) != 1:
target_day = first_day + datetime.timedelta(day + 7 - int(w))
else:
target_day = first_day + datetime.timedelta(day - int(w))
# 返回需要的字符串形式的日期
target_day = datetime.datetime.strftime(target_day, '%Y年%m月%d日')
return target_day
if __name__ == '__main__':
print(date_conversation(2021, 39))
输出结果:
2021年09月27日 进程已结束,退出代码为 0