将公开的Google日历活动导出为csv(Python)

gev0vcfq  于 2022-12-06  发布在  Go
关注(0)|答案(1)|浏览(159)

有一个公共的Google日历,我有它的日历ID。我想设置一个开始和结束日期,然后在一个CSV文件中获取这些日期之间的所有事件。在Python中最有效的方法是什么?
我找到的最接近的解决方案是https://stackoverflow.com/a/27213635/1936752,它产生一个json文件,没有按日期过滤。我可以用json文件做这件事,写一些代码只过滤我想要的日期,然后导出到csv,但我想有一个更聪明的方法?
我想要的手动方式是使用“导出日历”功能下载ics文件,然后使用像https://openicsfile.com/csv-convert.html这样的ics到csv转换。然后我可以轻松地过滤我想要的日期。我希望使用Python脚本来完成这一操作。

wr98u20j

wr98u20j1#

我相信你的目标如下。

  • 您希望从公开共享的Google日历中检索活动。
  • 您希望检索CSV文件形式的事件标题和日期。
  • 您希望使用python来实现这一点。

在这种情况下,下面的示例脚本如何?

示例脚本:

在此示例脚本中,事件列表是使用"Events: list" of Calendar API和API密钥检索的。因此,请检索您的API密钥。请在API控制台启用日历API。
并且,请设置以下示例脚本的变量。

import csv
from googleapiclient.discovery import build

api_key = "###" # Please set your API key.
calendar_id = "###" # Please set the calendar ID.
start = "2022-10-01T00:00:00Z" # Please set the start date you want to search.
end = "2022-10-31T00:00:00Z" # Please set the end date you want to search.

# Retrieve event list using googleapis for python.
service = build("calendar", "v3", developerKey=api_key)
events_result = service.events().list(calendarId=calendar_id, timeMin=start, timeMax=end, fields="items(summary,start,end)", timeZone="UTC").execute()

# Retrieve the event title and date from all-day events.
allDayEvents = [["Event title", "Date"], *[[e.get("summary"), e.get("start").get("date")] for e in events_result.get("items", []) if e.get("start").get("date") and e.get("end").get("date")]]

# Output the retrieved values as a CSV file.
with open("sample.csv", "w") as f:
    writer = csv.writer(f, lineterminator="\n")
    writer.writerows(allDayEvents)
  • 运行此脚本时,将使用API密钥从公开共享的Google日历中检索事件列表。然后,通过包含事件标题和日期创建CSV文件。在此示例中,将检索从2022年10月1日到2022年10月31日的全天事件。
  • 你可以在herehere上看到python的googleapis。

参考:

相关问题