使用python编写一段程序,程序要求:“输入一个日期,例如‘’20221001‘,输出该日期对应的节假日(也可能是周六或周末),如果不是节日就输出工作日’”。

使用python编写一段程序,程序要求:“输入一个日期,例如‘’20221001‘,输出该日期对应的节假日(也可能是周六或周末),如果不是节日就输出工作日’”。

img


这是什么问题,怎么解决呢
可以帮我写一个正确的全部代码吗

这个我刚好做过一个类似的项目
我先定义了一个函数,用于更新文本:

    def is_workdate(self, state: bool = True, weekdate: str = ""):
        if state:
            self.worker_label.config(text="[星期{}-工作日]".format(weekdate))
        else:
            self.worker_label.config(text="[星期{}-非工作日]".format(weekdate))

然后调用的时候通过下面这个函数获取是否工作日和周几:

    from workalendar.asia import China
    def is_workday(self):
        cal = China()
        date = datetime.datetime.now().date()
        weekdays = ["一", "二", "三", "四", "五", "六", "日"]
        return cal.is_working_day(date), weekdays[date.weekday()]

当然,这里的workalendar是要单独pip安装的,这个库每年都会更新一次

【相关推荐】



  • 这个问题的回答你可以参考下: https://ask.csdn.net/questions/7667171
  • 我还给你找了一篇非常好的博客,你可以看看是否有帮助,链接:python判断给定的日期是周几(2种方法) 、获取某一年每月的日历数据、获取法定节假日接口
  • 除此之外, 这篇博客: 非线性规划的拉格朗日乘子法的手工数学推导,考虑有约束情况的python代码中的 三、拉格朗日乘子法的有约束情况 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:

    在这里插入图片描述
    代码如下:

    from scipy.optimize import minimize
    import numpy as np
    e = 1e-10 # 非常接近0的值
    fun = lambda x : 8 * (x[0] * x[1] * x[2]) # 约束函数f(x,y,z) =8 *x*y*z
    cons = ({'type': 'eq', 'fun': lambda x: x[0]**2+ x[1]**2+ x[2]**2 - 1}, # x^2 + y^2 + z^2=1
            {'type': 'ineq', 'fun': lambda x: x[0] - e}, # x>=e,即 x > 0
            {'type': 'ineq', 'fun': lambda x: x[1] - e},
            {'type': 'ineq', 'fun': lambda x: x[2] - e}
           )
    x0 = np.array((1.0, 1.0, 1.0)) # 设置初始值
    res = minimize(fun, x0, method='SLSQP', constraints=cons)
    print('最大值:',res.fun)
    print('最优解:',res.x)
    print('迭代终止是否成功:', res.success)
    print('迭代终止原因:', res.message)
    

    在 jupyter notebook 中运行
    在这里插入图片描述
    运行结果:
    在这里插入图片描述


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^