タイムゾーン変換用の関数を定義する
異なるタイムゾーン間での会議調整を支援するスケジューリングアシスタントを作成しています。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)