0

任意の月の対応する週番号と組み合わせて営業日の日付を保存する Python スクリプトを作成するにはどうすればよいですか?

その質問は紛らわしいので、ここに「ビジュアル」があります:

August_2013 = {
  ( week1 : (8/1/2013),  (8/2/2013) ),
  ( week2 : (8/5/2013),  (8/6/2013),  (8/7/2013),  (8/8/2013),  (8/9/2013)  ),
  ( week3 : (8/12/2013), (8/13/2013), (8/14/2013), (8/15/2013), (8/16/2013) ),
  ( week4 : (8/19/2013), (8/20/2013), (8/21/2013), (8/22/2013), (8/23/2013) ),
  ( week5 : (8/26/2013), (8/27/2013), (8/28/2013), (8/29/2013), (8/30/2013) )
}

SO全体を検索して、2日間の営業日数を計算する次のコードを作成しました。

def businessDays(start_date, end_date):
  day_generator = (start_date + timedelta(x + 1) for x in xrange((end_date - start_date).days))
  holidays = [ date(2013, 7, 4), date(2013, 12, 25) ] # Will add more later
  return sum(1 for day in day_generator if day.weekday() < 5 and day not in holidays)

しかし、このコードでは十分ではありません。特定の月のどの週に何営業日あったかを知る必要があります。

編集: 私の OS は Windows 7 です。Python 2.7 を使用しています。

4

4 に答える 4

1

データをどのように保存したいのか正確にはわかりませんが、これはあなたが探しているものですか?

August_2013 = {}

def store(month, week, date):
    if week in month and date not in month[week]:
        month[week].append(date)
    else:
        month[week] = [date]

store(August_2013, "week1", "8/1/2013")
store(August_2013, "week1", "8/2/2013")
store(August_2013, "week2", "8/5/2013")

#calling August_2013 then returns {'week1': ['8/1/2013', '8/2/2013'], 'week2': ['8/5/2013']}

データにアクセスするには、次のようにします。

def access(month, week):
    return month[week]

access(August_2013, "week1") # will return ['8/1/2013', '8/2/2013']
于 2013-08-16T15:36:49.730 に答える
0

これを試して:

>>> import datetime
>>> def day_weekday(I_year, I_month):
    lst_weekday=[]
    lst_tmp=[]
    for day in range(1,32):
        try:
            day_temp=datetime.datetime(I_year, I_month, day)
            if day_temp.weekday() not in (6, 5):
                lst_tmp.append((I_year, I_month, day))
            elif len(lst_tmp)>0:
                lst_weekday.append(lst_tmp)
                lst_tmp=[]
            else:
                pass
        except ValueError:
            pass
    return lst_weekday, map(len, lst_weekday)

>>> day_weekday(2013, 8)
([[(2013, 8, 1), (2013, 8, 2)], \
 [(2013, 8, 5), (2013, 8, 6), (2013, 8, 7), (2013, 8, 8), (2013, 8, 9)], \
 [(2013, 8, 12), (2013, 8, 13), (2013, 8, 14), (2013, 8, 15), (2013, 8, 16)], \
 [(2013, 8, 19), (2013, 8, 20), (2013, 8, 21), (2013, 8, 22), (2013, 8, 23)], \
 [(2013, 8, 26), (2013, 8, 27), (2013, 8, 28), (2013, 8, 29), (2013, 8, 30)]], \
 [2, 5, 5, 5, 5])

この関数は 2 つのリストを返します。最初のものはリストのリストで、各リストはその週の平日です。2 つ目は、各週の曜日数です。必要な他の形式にフォーマットできます。

于 2013-08-16T16:44:04.717 に答える