GoogleカレンダーのエクスポートをPythonでCSVに 2020
GoogleカレンダーのエクスポートをPythonでCSVに 2020
旧版でエラー出たりタイムゾーンの修正などパッチあて
GoogleカレンダーでエクスポートしたデータをCSVにするPythonスクリ - boxheadroomのブログ
import zipfile
from datetime import datetime,timedelta
import codecs
folder="202001"
gid="hoge"
with zipfile.ZipFile(folder+"/"+gid+"@gmail.com.ical.zip" ,"r") as zp:
with zp.open(gid+"@gmail.com.ics","r") as fp:
lines=fp.read().decode("utf8").splitlines()
cursor=iter(lines)
h9=timedelta(9/24)
events=["DTSTART\tDTEND\tSUMMARY\tLOCATION"]
event={}
rep_pre={"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")+h9).strftime("%Y/%m/%d %H:%M:%S" )
,
"DTSTART;VALUE=DATE":lambda s:(datetime.strptime(
s,"%Y%m%d")+h9).strftime("%Y/%m/%d %H:%M:%S" )
}
rep_post={
"DTSTART;VALUE=DATE":"DTSTART",
"DTEND;VALUE=DATE": "DTEMD"}
filt["DTEND"]=filt["DTSTART"]
filt["DTEND;VALUE=DATE"]=filt["DTSTART;VALUE=DATE"]
curline=0
while True:
try:
ln=next(cursor)
curline+=1
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
ret=ln.split(":")
tag=ret[0]
content="_".join(ret[1:])
if tag in rep_pre:
tag=rep_pre[tag]
if tag in filt:
content=filt[tag](content)
if tag in rep_post:
tag=rep_post[tag]
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")