简体   繁体   中英

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.

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.

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())

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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