GoogleカレンダーでエクスポートしたデータをCSVにするPythonスクリ

自分用やっつけ

2020-01 修正 今後は こっち使う

boxheadroom.hatenablog.com


import zipfile
from datetime import datetime
import codecs
with zipfile.ZipFile("foo@gmail.com.ical.zip" ,"r") as zp:
with zp.open("foo@gmail.com.ics","r") as fp:
lines=fp.read().decode("utf8").splitlines()
cursor=iter(lines)
events=[ "DTSTART\tDTEND\tSUMMARY\tLOCATION"]
event={}
rep={"DTSTART;TZID=Asia/Tokyo":"DTSTART",
"DTEND;TZID=Asia/Tokyo:":"DTEND" }
filt={
"DTSTART":lambda s:datetime.strptime(
s.replace("Z",""),"%Y%m%dT%H%M%S").strftime("%Y/%m/%d %H:%M:%S" )
}
filt["DTEND"]=filt["DTSTART"]
while True:
try:
ln=next(cursor)
if ln=="BEGIN:VEVENT":
event={"VEVENT":""}
elif ln=="END:VEVENT":
if not "DTEND" in event:
event["DTEND"]=event["DTSTART"]

events.append("{DTSTART}\t{DTEND}\t{SUMMARY}\t{LOCATION}".format(**event))
event={}
else:
if not "VEVENT" in event:
continue
tag,content=ln.split(":")
if tag in rep:
tag=rep[tag]
if tag in filt:
content=filt[tag](content)
event[tag]=content
except StopIteration:
break
with codecs.open("gcal.csv","w","utf8") as fp:
fp.write("\n".join(events))
for e in events:
print(e)
print("done")