如何改造Python代码实现Google Calendar今日事件的获取
Fetch Today's Events from Google Calendar API
To get only today's events, you'll use the Google Calendar API's timeMin and timeMax query parameters to filter events within the start and end of today. Here's how to modify your code:
Step-by-Step Explanation
- Calculate today's time bounds: We need the start of today (midnight UTC) and start of tomorrow (midnight UTC) to cover all events occurring on today.
- Format dates to ISO 8601: The API requires timestamps in
YYYY-MM-DDTHH:MM:SSZformat (UTC). - Add query parameters: Pass these time bounds as
timeMinandtimeMaxin your GET request. Optionally, usesingleEvents=trueto include recurring events as individual instances.
Modified Code
import requests from datetime import datetime, timedelta # Calculate today's start and end times in UTC today_start = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0) today_end = today_start + timedelta(days=1) # Format to ISO 8601 string (required by Google Calendar API) time_min = today_start.isoformat() + 'Z' time_max = today_end.isoformat() + 'Z' # API endpoint with your calendar ID url = "https://www.googleapis.com/calendar/v3/calendars/***calendarId***/events" # Query parameters to filter today's events params = { 'timeMin': time_min, 'timeMax': time_max, 'singleEvents': 'true', # Optional: expands recurring events to individual instances 'orderBy': 'startTime' # Optional: sorts events by start time } headers = { 'Authorization': 'Bearer *************************************************' } # Send GET request with parameters response = requests.get(url, headers=headers, params=params) # Print the response (or parse it as JSON for easier handling) print(response.text) # Alternatively, parse to JSON for structured access: # import json # events_data = json.loads(response.text) # for event in events_data.get('items', []): # event_name = event['summary'] # event_start = event['start'].get('dateTime', event['start'].get('date')) # print(f"{event_name} - Starts at: {event_start}")
Additional Notes
- Time Zone Adjustments: If your calendar uses a non-UTC time zone, you'll need to calculate
today_startandtoday_endin that timezone instead of UTC. For Python 3.9+, usezoneinfo; for older versions, usepytz. Example withzoneinfo:from zoneinfo import ZoneInfo tz = ZoneInfo('America/New_York') today_start = datetime.now(tz).replace(hour=0, minute=0, second=0, microsecond=0) today_end = today_start + timedelta(days=1) # Convert to UTC for the API time_min = today_start.astimezone(ZoneInfo('UTC')).isoformat() + 'Z' time_max = today_end.astimezone(ZoneInfo('UTC')).isoformat() + 'Z' - Error Handling: You might want to add checks for HTTP errors (e.g.,
response.raise_for_status()) to catch issues like invalid tokens or calendar IDs quickly.
Content of the question originates from Stack Exchange, question author User1
相关产品推荐
相关产品推荐

