【问题标题】:How to determine if 4th day of the month (Mon and Sun not included)如何确定一个月的第 4 天(不包括周一和周日)
【发布时间】:2020-09-03 16:10:54
【问题描述】:

我知道 pandas 有 weekday() 它将星期几作为整数返回(0 表示星期一和 6 星期日)但我想不出如果今天的当前日期是 4 号将返回 True 的解决方案一个月中的某一天,而忽略周日和周一,考虑到时间表仅从周二到周六运行。

有人遇到过这个吗?

【问题讨论】:

  • 提示:使用and
  • 这不是if (day == 4 and (weekday not in (0, 6))这么简单吗?
  • @Max 我认为 OP 想要找到本月的第 4 个工作日,但那不会。
  • 一般来说这应该是一个非常简单的算法。如果是星期五并且是第 4 个工作日,那么它也是第 4 个工作日。如果是星期二,则必须是第 6 个工作日才能成为第 4 个工作日。您只需要为一周中的特定日期加/减 2……我将把细节留给读者作为练习。
  • Chesterae:你是指一个月的第四个营业日吗?

标签: python date datetime


【解决方案1】:

解决此类问题的典型方法是构建一个表: 对于一周中的每一天,问问自己:如果月初是一周中的那一天,我希望我的活动在一周中的哪一天/一周中发生。

编写一个谓词,该谓词恰好在这 7 个星期几/每月几日的组合上返回 true,仅此而已。

【讨论】:

    【解决方案2】:

    此功能将通过创建不包括周末的日期序列来帮助您做到这一点。请注意,输入应该是一个日期对象(例如 datetime.now().date())

    from datetime import datetime, timedelta
    def is_4th(d):
        # get month start
        month_start = datetime(d.year,d.month,1).date()
        # create a date sequence from start of month excluding the weekends
        date_seq = [(month_start + timedelta(days=i)) for i in range(0, 7) if (month_start+timedelta(days=i)).weekday() not in [5,6]]
        # if 4th day in the sequence is equal to the date then return true else false
        if d ==date_seq[3]:
            return True
        return False
    
    

    【讨论】:

    • 谢谢你,但是运行顺序从周二到周六开始,所以我只需将 [5, 6] 中的 not 更改为 [0, 6]。
    猜你喜欢
    • 2019-04-24
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多