การสร้างฟังก์ชันสำหรับแปลง Timezone
กำลังสร้างผู้ช่วยจัดตารางประชุมที่ช่วยประสานงานการประชุมข้ามโซนเวลาต่าง ๆ OpenTimezone API ให้บริการแปลง timezone โดยเพียงส่งวันและเวลา timezone ต้นทาง และ timezone ปลายทาง ก็จะได้รับเวลาที่แปลงแล้วกลับมา งานของคุณคือสร้างฟังก์ชันที่เรียกใช้ API นี้และคืนค่าผลลัพธ์ในรูปแบบที่กำหนด
โมดูล requests และ json ได้นำเข้ามาให้เรียบร้อยแล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การทำงานกับ OpenAI Responses API
คำแนะนำการฝึกหัด
- กำหนดค่าตัวแปร
urlเป็น"https://api.opentimezone.com/convert" - สร้าง dictionary ชื่อ
payloadโดยมีคีย์"dateTime","fromTimezone", และ"toTimezone"ที่แมปกับอาร์กิวเมนต์ของฟังก์ชัน - ส่งคำขอแบบ POST ไปยัง
urlโดยกำหนด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)