1

谷歌日历有什么方法可以简单地为我提供事件发生的星期几的名称?例如,如果我检索一个日期范围内的事件列表,如下所示:

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

有没有办法在该列表中查找特定事件并找出它在哪一天?现在我正在使用一个尴尬的技巧,涉及 Google Calendar API 中的“date”和“dateTime”以及 Python 的 calendar 模块:

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

据我所知,没有直接的方法可以在日历 API 中获取事件的日期。如果结果的日期格式与参数 ( 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并迭代两个事件之间的天数(请注意,这有点随意,但希望能提供一个有用的例子):

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 回答