Định nghĩa hàm để chuyển đổi múi giờ
Bạn đang xây dựng một trợ lý lập lịch giúp phối hợp họp xuyên múi giờ. OpenTimezone API cung cấp dịch vụ chuyển đổi múi giờ — bạn chỉ cần gửi thời điểm datetime, múi giờ nguồn và múi giờ đích, và API sẽ trả về thời gian đã được chuyển đổi. Nhiệm vụ của bạn là tạo một hàm gọi API này và trả về kết quả đã định dạng.
Các mô-đun requests và json đã được nhập sẵn cho bạn.
Bài tập này là một phần của khóa học
Làm việc với OpenAI Responses API
Hướng dẫn bài tập
- Gán biến
urlbằng"https://api.opentimezone.com/convert". - Tạo một dictionary
payloadvới các khóa"dateTime","fromTimezone", và"toTimezone"ánh xạ tới các đối số của hàm. - Thực hiện yêu cầu POST tới
url, truyềnpayloadở dạng JSON. - Kiểm tra hàm hoạt động với các giá trị đã cung cấp.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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)