定义一个用于转换时区的函数
您正在构建一个日程助手,用于协调不同时区的会议。OpenTimezone API 提供时区转换服务——您只需发送日期时间、源时区和目标时区,它就会返回转换后的时间。您的任务是创建一个函数,调用该 API 并返回格式化的结果。
本题已为您导入 requests 和 json 模块。
本练习是课程的一部分
使用 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)