简体   繁体   English

如何从星期几获取月几号?

[英]How to obtain day of the month from day of the week?

I'm trying to get python to return the date of the month when a day of the week is inputed eg: 1st Sunday of April 2018 returns 1 or 3rd Thursday of April 2018 returns 19 我正在尝试让python返回输入星期几的月份的日期,例如:2018年4月的第1个星期日返回1或2018年4月的第3个星期四返回19

Are there python libraries or mathematical algorithms that do this? 是否有执行此操作的python库或数学算法? I've looked at Zeller's congruence but it seems like it does the opposite. 我看过Zeller的一致性,但似乎却恰恰相反。

From your Input string separating all the values and then takes all the dates of that day from that month in that year. 从输入字符串中分离所有值,然后获取该年中该月中该天的所有日期。

Here a big try : 这是一个很大的尝试:

import calendar
import re

c = calendar.Calendar(firstweekday=calendar.SUNDAY)

string = "1st Sunday of April 2018"
string.split().pop(2)
string_list = string.split()
year = int(string_list[4])
month = list(calendar.month_name).index(string_list[3])
day_num = list(calendar.day_name).index(string_list[1])
which = int(re.search(r'\d+', string_list[0]).group())

monthcal = c.monthdatescalendar(year,month)
date = [day for week in monthcal for day in week if \
            day.weekday() == day_num and \
            day.month == month][which-1]

print(date.day)

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

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