Bắt đầu ngayBắt đầu miễn phí

Đị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 requestsjson đã đượ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

Xem khóa học

Hướng dẫn bài tập

  • Gán biến url bằng "https://api.opentimezone.com/convert".
  • Tạo một dictionary payload vớ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ền payload ở 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)
Chỉnh sửa và Chạy Mã