開始使用免費開始

定義用於轉換時區的函式

你正在打造一個行程助理,協助在不同時區之間協調會議。OpenTimezone API 提供時區轉換服務——你只要送出日期時間、來源時區與目標時區,它就會回傳轉換後的時間。你的任務是撰寫一個函式,呼叫這個 API,並回傳格式化的結果。

requestsjson 模組已經替你匯入。

本練習屬於課程

使用 OpenAI Responses API

檢視課程

練習說明

  • 將變數 url 設為 "https://api.opentimezone.com/convert"
  • 建立 payload 字典,包含鍵 "dateTime""fromTimezone""toTimezone",分別對應到函式的引數。
  • url 發出 POST 請求,並將 payload 指定為 JSON。
  • 使用提供的數值測試此函式是否可正常運作。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def convert_timezone(date_time: str, from_timezone: str, to_timezone: str) -> str:
    """
    Convert a datetime from one timezone to another.
    
    Args:
        date_time: The datetime string in ISO format
        from_timezone: Source timezone
        to_timezone: Target timezone
    
    Returns:
        A string with the converted datetime and timezone information
    """
    # Set the API endpoint
    url = "____"
    
    # Prepare the request payload
    payload = {"dateTime": ____, "fromTimezone": ____, "toTimezone": ____}
    
    try:
        # Make the API request and extract converted time
        response = requests.post(url, json=____)
        response.raise_for_status()
        
        data = response.json()
        converted_time = data.get('dateTime', 'N/A')
        
        return f"Time in {to_timezone}: {converted_time}"
    
    except requests.exceptions.RequestException as e:
        return f"Error converting timezone: {str(e)}"

# Test the function
result = convert_timezone('2025-01-20T14:30:00', 'America/New_York', 'Europe/London')
print(result)
編輯並執行程式碼