栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Python

【趣味编程】根据年份和周数获取第n周周一对应的日期(经济政治上的周一)

Python 更新时间:发布时间: 百科书网 趣学号
【趣味编程】根据年份和周数获取第n周周一对应的日期(经济政治上的周一)
#!/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
转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/280450.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号