0

I'm trying to get the start/end dates of the 7-day date range where the following are true (given a month and year):

  • Starts on a Saturday
  • Ends on the following Friday
  • Has at least 4 of its 7 days in the given month (meaning up to 3 can be in the next month)
  • Is the last date range in the month that meets these conditions

For example, if I were to get this period for the month of August 2020, the result would be 8/22 to 8/28. If I were to do the same for June 2020, the result would be 6/27 to 7/3.

Does anyone have any ideas? Thank you!

Ben Soyka
  • 816
  • 10
  • 25
  • Take a look at the module `dateutil`. – BoarGules Aug 30 '20 at 16:46
  • 2
    Your conditions boil down to "The week containing the last Tuesday of the month" – Blckknght Aug 30 '20 at 17:02
  • 1
    And here's an answer for how to get the last Tuesday of the month: [Print date of last Tuesday of each month of next year using Python](https://stackoverflow.com/questions/44305610/print-date-of-last-tuesday-of-each-month-of-next-year-using-python) – Craig Aug 30 '20 at 17:09
  • Thank you so much @Blckknght, I didn't even think of that. – Ben Soyka Aug 30 '20 at 17:22

1 Answers1

0

Please test the following code. I'd be really happy if you let me know the result.

import datetime, calendar

import dateparser

def get_date_range(input_dt):
    r = dateparser.parse(input_dt)
    year = r.year
    month = r.month
    day = r.day

    last_date = calendar.monthrange(year, month)[1]
    full_end_date = dateparser.parse(f"{last_date}/{month}/{year}")
    lastFriday = full_end_date
    oneday = datetime.timedelta(days=1)

    while lastFriday.weekday() != calendar.SATURDAY:
        lastFriday -= oneday

    days_in_given_month = (full_end_date - lastFriday).days + 1
    if days_in_given_month < 4:
        start_date = lastFriday - datetime.timedelta(days=7)
        end_date = start_date + datetime.timedelta(days=6)
        start_date_str = start_date.strftime('%m/%d/%Y')
        end_date_str = end_date.strftime('%m/%d/%Y')
    else:
        end_date = lastFriday + datetime.timedelta(days=6)
        start_date_str = lastFriday.strftime('%m/%d/%Y')
        end_date_str = end_date.strftime('%m/%d/%Y')

    return [start_date_str, end_date_str]

input_dt = "June 2020"
# input_dt = "August 2020"

r = get_date_range(input_dt)
print(r)
Ahmed Mamdouh
  • 696
  • 5
  • 12