1

Google カレンダーでイベントが発生する曜日の名前を簡単に表示する方法はありますか? たとえば、次のように、日付の範囲内でイベントのリストを取得するとします。

events = service.events().list(calendarId='primary', timeMin='2012-12-24T00:00:00Z',
 timeMax='2012-12-30T23:59:59Z').execute()

そのリスト内の特定のイベントを調べて、その日が何日かを調べる方法はありますか? 現在、Python のカレンダー モジュールと組み合わせた Google Calendar API の「date」と「dateTime」を含む厄介なハックを使用しています。

for calendar_list_entry in events['items']:
    try:
        year, month, day = calendar_list_entry['start']['date'].split('-')
        dayNum = calendar.weekday(int(year), int(month), int(day))
        print dayNum
        dayName = createDayName(dayNum)
        dayDict[dayName].append(calendar_list_entry['summary'])
        print dayDict[dayName]
    except:
        print calendar_list_entry['start']['dateTime'][:10].split('-')
        year, month, day = calendar_list_entry['start']['dateTime'][:10].split('-')
        dayNum = calendar.weekday(int(year), int(month), int(day))
        print dayNum
        dayName = createDayName(dayNum)
        dayDict[dayName].append(calendar_list_entry['summary'])
        print dayDict[dayName]

createDayName 関数は単純です。

def createDayName(dayNum):
    '''
    Takes as input a number generated from calendar.weekday and outputs the weekday name
    that is associated with that number.
    '''
    dayNameList = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
    return dayNameList[dayNum]

確かにこれを行うための面倒でない方法はありますか?また、木曜から土曜など、複数の日にまたがるイベントでも深刻な問題に遭遇します。日を分割するためにばかげた計算を行うことができることはわかっていますが、そのような単純な操作にはもっと良い方法があるはずです.

4

1 に答える 1

2

私の知る限り、CalendarAPIでイベントの日を取得する直接的な方法はありません。結果の日付形式がパラメーター()の場合と同じである場合は、モジュール2012-12-24T00:00:00Zと組み合わせて文字列形式を使用できます。datetimeここで、は、対応する形式で文字列を%A実行することによって定義された日時オブジェクトの曜日を返す文字列フォーマットパラメータです。strptime

In [1]: from datetime import datetime

In [2]: s = '2012-12-24T00:00:00Z'

In [3]: d = datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')

In [4]: '{0:%A}'.format(d)
Out[4]: 'Monday'

そして関数として:

In [8]: def createDayName(s):
   ...:     d = datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')
   ...:     return '{0:%A}'.format(d)
   ...: 

In [9]: createDayName('2012-12-24T00:00:00Z')
Out[9]: 'Monday'

In [10]: createDayName('2012-12-30T23:59:59Z')
Out[10]: 'Sunday'

その上で、複数日のイベントを処理する必要がある場合は、このようなものを試すことができます。ここでは、メインピースが含まtimedeltaれ、2つのイベント間の日数を繰り返します(これは少し恣意的ですが、うまくいけば、便利な例):

from datetime import datetime, timedelta

# This structure will allow us to append to our dictionary without
# there needing to be a key first (comes in handy)
from collections import defaultdict


def days_in_range(start, end, daysDict):
    # Convert your start/end dates
    start_d = datetime.strptime(start, '%Y-%m-%dT%H:%M:%SZ')
    end_d = datetime.strptime(end, '%Y-%m-%dT%H:%M:%SZ')

    # Now iterate over the days between those two dates, adding
    # an arbitrary value to the 'day' key of our dict
    for i in range((end_d - start_d).days + 1):
        day_name = '{0:%A}'.format(start_d + timedelta(days=i))
        daysDict[day_name].append(i)
    return daysDict


# Create your dictionary that will have a list as the default value
daysDict = defaultdict(list)

start = '2012-12-24T00:00:00Z'
end = '2012-12-30T23:59:59Z'

# I would probably reevaluate this part, but the reason for
# passing the dictionary itself to the function is so that
# it can better fit into situations where you have multiple events
# (although a class structure may be well-suited for this, but
# that may be overcomplicating things a bit :) )
daysDict = days_in_range(start, end, daysDict)

for day, value in daysDict.iteritems():
  print day, value

これにより、次のように出力されます(辞書は本質的に順序付けされていないため、表示が異なる場合があります)。

Monday [0]
Tuesday [1]
Friday [4]
Wednesday [2]
Thursday [3]
Sunday [6]
Saturday [5]
于 2012-12-29T02:15:24.647 に答える