始める無料で始める

タイムゾーン変換用の関数を定義する

異なるタイムゾーン間での会議調整を支援するスケジューリングアシスタントを作成しています。OpenTimezone API はタイムゾーン変換を提供します。日時、変換元のタイムゾーン、変換先のタイムゾーンを送るだけで、変換後の時刻が返ってきます。あなたの課題は、この API を呼び出して整形済みの結果を返す関数を作成することです。

requests モジュールと json モジュールはすでにインポート済みです。

この演習はコースの一部です

OpenAI Responses API を使いこなす

コースを見る

演習の手順

  • url 変数に "https://api.opentimezone.com/convert" をセットします。
  • 関数の引数に対応するキー "dateTime""fromTimezone""toTimezone" を持つ payload 辞書を作成します。
  • payload を JSON として url に POST リクエストを送ります。
  • 提示された値で関数が動作するかテストしましょう。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

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)
コードを編集して実行