简体   繁体   English

是否有相当于 Java 的 Calendar.DAY_OF_WEEK_IN_MONTH 的 Python?

[英]Is there a Python equivalent of Java's Calendar.DAY_OF_WEEK_IN_MONTH?

My aim is to find which nth day of week in the month is a given date?我的目标是找出一个月中的第 n 天是给定日期? For example, I want to be able to have the following:例如,我希望能够拥有以下内容:

Input : Input

21 December 2020 2020 年 12 月 21 日

Output : Output

3rd Monday of this month本月第三个星期一

Java's Calendar library does exactly what I need as illustrated here . Java 的日历库正是我所需要的,如此处所示 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).寻找 Python 等价物或指向相同的现有答案(我尝试了很多寻找但徒劳无功。所以我放弃了,作为最后的手段在这里问)。

AFAIK there is no built-in function for this, but it's easy to implement: AFAIK 没有内置的 function ,但它很容易实现:

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).当然,对于字符串表示,您需要考虑几个序数指示符(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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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