-2

I wondered how to check if the current day is the first weekday of the month in Python and could not find any solution on the web. So I thought I post mine, in case anyone needs to solve this too.

stack_lech
  • 990
  • 2
  • 10
  • 28

2 Answers2

2
import datetime

weekday = datetime.datetime.today().weekday()
day = datetime.datetime.today().day
date_str = datetime.datetime.today().strftime("%A, %d-%m-%Y")

if (weekday == 0 and day in (1, 2, 3)) or (weekday in (1, 2, 3, 4) and day == 1):
    print("Today {0} is the first weekday of the month.".format(date_str))
else:
    print("Today {0} is not the first weekday of the month.".format(date_str))

datetime.datetime.today().weekday() returns the weekday as integer where 0 = Monday, 1 = Tuesday etc.

datetime.datetime.today().day returns the day of the month as integer

The first Monday of the month can either be the 1st, 2nd or 3rd of the month. All other weekdays have to be checked if they are on the 1st of the month. If they are not on the first of the month they're not the first weekday of the month.

stack_lech
  • 990
  • 2
  • 10
  • 28
0

When you said first weekday you are supposing Monday right?

The logic behind this should be:

  • Today is Monday
  • Today is 1, 2, 3, 4, 5, 6 or 7
  • Latest is because, if today is Monday but is 8 that it means first Monday was the 1st

A function to get this its

def is_first_weekday_of_month():
    weekday = datetime.today().weekday()
    day = datetime.today().day

    return weekday == 0 and day in (1, 2, 3, 4, 5, 6, 7)
Darkaico
  • 1,206
  • 9
  • 11