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

这是一个Python程序,用于计算给定年份和周数对应的第n周周一的日期。程序首先将输入的年份和周数转换为整型,然后通过datetime和calendar模块确定当年的第一天,并计算出目标周一的日期。如果输入的周数超出范围,程序会给出警告并提示重新输入。程序最终会以指定格式输出日期,并提供确认对话框。
摘要由CSDN通过智能技术生成

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

#!/usr/bin/env python
# -*- coding = utf-8 -*-
# @Time : 2021/9/30 20:55
# @Author : 陈良兴
# @File : test_week
# @Software : PyCharm

import datetime
from calendar import *
import pyautogui

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__':
    while True:
        year = input("年份:")
        week = input("第几周:")
        if int(week) <= 53:
            text = "{}年的第{}周周一对应的日期为:".format(year, week) + date_conversation(year, week)
            print(text)
            print("---------------------------------------------------------------------------------------------")
            bottons = ['OK', 'Cancel']
            b = pyautogui.confirm(text=text, title='result', buttons=bottons)
            if len(b) == 2:
                continue
            else:
                break
        else:
            bottons = ['OK', 'Cancel']
            a = pyautogui.confirm(text=r'周数错误,一年周数为53,请输入小于或等于53的数!!!', title='警告', buttons=bottons)
            if len(a) == 2:
                continue
            else:
                break

输出结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值