简体   繁体   中英

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

Are there python libraries or mathematical algorithms that do this? I've looked at Zeller's congruence but it seems like it does the opposite.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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