2014-11-21 98 views
0

在給定年份,月份和星期編號(第1,第2,第3等)的情況下,有沒有辦法查找特定周內的日期範圍?我已經看到很多關於如何查找基於特定日期的星期數的答案,但我正在嘗試根據星期數找到日期。舉例來說,(2013,9,「星期四」,「第3」)給出了結果(2013,9,19)。根據python的月份查找日期

這裏是我到目前爲止的代碼(僅適用於在「teenth」結束日期):

from datetime import date 

def meetupday(year, month, weekday, word): 
    weekday_dic = {"Monday": 0, "Tuesday": 1, "Wednesday": 2, "Thursday": 3, 
       "Friday": 4, "Saturday": 5, "Sunday": 6} 
    week_of_the_month = {"1st": 1, "2nd": 2, "3rd": 3, "4th": 4, "last": 5} 
    if word == "teenth": 
     for day in xrange(13, 20): 
     if weekday_dic[weekday] == date(year, month, day).weekday(): 
      return year, month, day 
    else: 
    for date in xrange(1, amount_of_days+1): 
     date_data = datetime.date(year, month, date).isocalendar() 
     if date_data[2] == weekday_dic[weekday]+1: 
      return year, month, week_of_the_month[word] 

這是exercism.io的聚會問題。

回答

1

我的解決方案基於您給定的數據的日期將是類似的東西

from datetime import datetime, timedelta  
weekday_dic = {"Monday": 0, "Tuesday": 1, "Wednesday": 2, "Thursday": 3, 
        "Friday": 4, "Saturday": 5, "Sunday": 6} 
week_of_the_month = {"1st": 1, "2nd": 2, "3rd": 3, "4th": 4, "last": 5} 

start_first_week = first_sunday = datetime(year, month, 1) 
while start_first_week.weekday() != weekday_dic[weekday]: 
    start_first_week += timedelta(days=1) 

start_first_week += timedelta(days=(week_of_the_month[word] - 1) * 7) 

我希望幫助你一點

+0

哇,與我的相比,這太神奇了!非常感謝! – Drivebyluna 2014-11-23 04:03:35

1

一個快速的問題,我發現了達達主義的解決方案是,當我試圖計算每年美國陣亡將士紀念日的日期(5月的最後一個星期一)。我會得到2018-06-04。根據我的參數,這不是正確的月份。如果輸出月份與輸入不匹配,我添加了一個快速修復,只需要減去7天。我不確定底層問題是什麼。現在返回正確答案:2018-05-28。

from datetime import datetime, timedelta  
weekday_dic = {"Monday": 0, "Tuesday": 1, "Wednesday": 2, "Thursday": 3, 
         "Friday": 4, "Saturday": 5, "Sunday": 6} 
week_of_the_month = {"1st": 1, "2nd": 2, "3rd": 3, "4th": 4, "last": 5} 

start_first_week = first_sunday = datetime(year, month, 1) 
while start_first_week.weekday() != weekday_dic[weekday]: 
    start_first_week += timedelta(days=1) 

start_first_week += timedelta(days=(week_of_the_month[word] - 1) * 7) 
if start_first_week.month != month: 
    start_first_week += datetime.delta(days=-7) 
相關問題