You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何改造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:SSZ format (UTC).
  • Add query parameters: Pass these time bounds as timeMin and timeMax in your GET request. Optionally, use singleEvents=true to 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_start and today_end in that timezone instead of UTC. For Python 3.9+, use zoneinfo; for older versions, use pytz. Example with zoneinfo:
    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:23:14