简体   繁体   English

如何确定每月的第 4 天(不包括星期一和星期日)

[英]How to determine if 4th day of the month (Mon and Sun not included)

I know pandas has weekday() which returns the day of the week as an integer (0 as Monday and 6 Sunday) but I can't think of solution that will return True if the current date today is the 4th day of the month while disregarding Sunday and Monday, considering the schedule runs only from Tuesday to Saturday.我知道大熊猫有weekday()它将星期几作为整数返回(0 为星期一和 6 星期日),但我想不出如果今天的当前日期是该月的第 4 天,则返回True的解决方案不考虑星期日和星期一,考虑到时间表只从星期二运行到星期六。

Is there anyone came across with this?有没有人遇到过这个?

The typical way to solve problems like these is just to build a table: For each day of the week, ask yourself: If the first of the month falls on that day of the week, what day of the month/day of the week do I want my event to happen on.解决此类问题的典型方法就是建立一个表格:对于一周中的每一天,问问自己:如果一个月的第一天是一周中的那一天,那么该月的哪一天/一周的哪一天我希望我的活动继续进行。

Write a predicate that returns true on precisely those 7 day-of-week/day-of-month combinations and nothing else.编写一个谓词,该谓词在这 7 个星期几/月份的第 7 天组合上返回 true,没有别的。

This function will help you do that by creating a date sequence excluding weekends.此功能将通过创建不包括周末的日期序列来帮助您做到这一点。 Please note that the input should be a date object (eg datetime.now().date())请注意,输入应该是日期对象(例如 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM