0

My aim is to find which nth day of week in the month is a given date? For example, I want to be able to have the following:

Input:

21 December 2020

Output:

3rd Monday of this month

Java's Calendar library does exactly what I need as illustrated here. Looking for a Python equivalent or an already existing answer pointing to the same (I tried a lot to find but in vain. So I gave up and am asking here as a last resort).

sri
  • 744
  • 7
  • 20
  • This Stack Overflow entry already addresses your question: https://stackoverflow.com/questions/9847213/how-do-i-get-the-day-of-week-given-a-date – Pretzel Dec 21 '20 at 16:07
  • @Pretzel No it doesn't. My question pertains to the occurrence of the day of the week in month, not the actual position of day in the week. – sri Dec 21 '20 at 16:22
  • Did you read further down in that post? It talks about `import calendar` and using a function in there to get the day of the week. – Pretzel Dec 21 '20 at 16:42
  • I checked all the answers that contain `import calendar` statement. None of them answer my specific question. There is a major difference between getting just the weekday and getting the weekday occurrence in month. Did you read the `Output` clause that I mentioned above? – sri Dec 23 '20 at 04:58

1 Answers1

1

AFAIK there is no built-in function for this, but it's easy to implement:

from datetime import date
from math import ceil

d = date.fromisoformat('2020-12-21')
d.strftime(f"{(dom := (ceil(d.day / 7)))}{'rd' if dom > 1 else 'st'} %A of this Month")

Of course, for string representation, you need to take into account the several ordinal indicators (st, nd, rd, th). If you, on the other hand, just want to get the number of the month occuring, you can just use:

ceil(d.day / 7)
Richard Neumann
  • 2,986
  • 2
  • 25
  • 50