目标:创建Google日历活动。
阻止程序:日期格式。
背景:我正在尝试创建一个膳食计划器,该计划器从给定的数据库中获取食谱,并在Google日历中创建事件及其名称。该数据库如下所示:
d = {'recipe_id': ['carrot salad', 'leek fritters'], 'meal_date': ['2020-05-28 22:28:01.204464+00:00', '2020-05-29 22:28:01.204464+00:00']}
df = pd.DataFrame(data=d)
用餐日期是两个的乘积
today_date = datetime.datetime.utcnow().isoformat() + 'Z'
df['menu_date'] = today_date
df['menu_date'] = pd.to_datetime(df['menu_date'])
df['meal_date'] = df['menu_date'] + df['meal'].apply(pd.offsets.Day)
“餐”只是一个数字(1、2等),最后一条命令只是将今天的日期移动了该数量。
当我使用以下代码上传到Google日历时,出现错误:
def myconverter(o):
'''
call the __str__ method of the datetime object that will return a string representation of the value
___
shoutout: https://code-maven.com/serialize-datetime-object-as-json-in-python
'''
if isinstance(o, datetime.datetime):
return o.__str__()
def add_to_calendar(df, calendar_id):
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
# Call the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
print('Adding meals to calendar')
for i, r in df.iterrows():
event = {
'summary': r.name,
'description': r.meal_period,
'start': {
'date': json.dumps(r.meal_date, default=myconverter),
'timeZone': 'America/Los_Angeles'
},
'end': {
'date': json.dumps(r.meal_date, default=myconverter),
'timeZone': 'America/Los_Angeles'
}
}
event = service.events().insert(calendarId=calendar_id, body=event).execute()
运行此代码,出现以下错误:
HttpError: <HttpError 400 when requesting https://www.googleapis.com/calendar/v3/calendars/CALENDAR_ID/events?alt=json returned "Invalid value for: Invalid format: ""2020-05-28 22:28:01.204464+00:00""">
其中CALENDAR_ID是我的Google日历ID。
如果有人知道如何使用python代码解决此日期问题,这将非常有用。
这个答案怎么样?
start.date
和end.date
作为全天活动,则格式必须为yyyy-mm-dd
。在这种情况下,不需要timeZone。start.dateTime
和end.dateTime
作为全天活动,则格式必须为RFC3339。在这种情况下,需要timeZone。在上述情况下,修改脚本后,以下模式如何?
在此模式下,使用start.date
和end.date
。为此,请进行如下修改。
'start': {
'date': json.dumps(r.meal_date, default=myconverter),
'timeZone': 'America/Los_Angeles'
},
'end': {
'date': json.dumps(r.meal_date, default=myconverter),
'timeZone': 'America/Los_Angeles'
}
'start': {
'date': 'date': parse(r.meal_date).strftime("%Y-%m-%d"),
},
'end': {
'date': 'date': parse(r.meal_date).strftime("%Y-%m-%d"),
}
在此模式下,使用start.dateTime
和end.dateTime
。为此,请进行如下修改。
'start': {
'date': json.dumps(r.meal_date, default=myconverter),
'timeZone': 'America/Los_Angeles'
},
'end': {
'date': json.dumps(r.meal_date, default=myconverter),
'timeZone': 'America/Los_Angeles'
}
'start': {
'dateTime': parse(r.meal_date).isoformat(),
'timeZone': 'America/Los_Angeles'
},
'end': {
'dateTime': parse(r.meal_date).isoformat(),
'timeZone': 'America/Los_Angeles'
}
from dateutil.parser import parse
。https://www.googleapis.com/auth/calendar
作为范围。那时,请删除token.pickle
文件并重新授权范围。请注意这一点。