-1

So ive been looking around to find how to save a value as the last sunday of the current month. I mean if we are in july, last sunday of the month would be 25/07. The intent is to make a bot reply with the : Next payout wil be "last.sunday.month" for example.

Can anyone help?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 2
    Does this answer your question? [get the last sunday and saturday's date in python](https://stackoverflow.com/questions/18200530/get-the-last-sunday-and-saturdays-date-in-python) – Brian Destura Jul 10 '21 at 00:55
  • No, because in this case as I can see, it refers to last sunday as previous sunday. I want to gather the current month and then the last sunday of this current month . Thanks – jabaquara Jul 10 '21 at 01:01
  • If you apply the algorithm from the linked question to [the last day of the current month](https://stackoverflow.com/q/42950/9997212), then it'll return the last sunday of this month. – enzo Jul 10 '21 at 01:10
  • Can you help me that? im new to coding. ive doing a chatbot for past 2 days now. – jabaquara Jul 10 '21 at 01:31

1 Answers1

1

The general algorithm is to get the first Sunday of next month, then subtract 7 days.

def last_sunday(year, month):
    if month == 12:
        year += 1
        month = 1
    else:
        month += 1
    dt = datetime.datetime(year, month, 1)
    dt += datetime.timedelta(days=6-dt.weekday()) # first Sunday
    dt -= datetime.timedelta(days=7)
    return dt
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622