LoslegenKostenlos loslegen

Defining a Function for Converting Timezones

You're building a scheduling assistant that helps coordinate meetings across different timezones. The OpenTimezone API provides timezone conversion services—you just need to send it a datetime, source timezone, and target timezone, and it returns the converted time. Your task is to create a function that makes this API call and returns a formatted result.

The requests and json modules have already been imported for you.

Diese Übung ist Teil des Kurses

Working with the OpenAI Responses API

Kurs anzeigen

Anleitung zur Übung

  • Set the url variable to "https://api.opentimezone.com/convert".
  • Create a payload dictionary with keys "dateTime", "fromTimezone", and "toTimezone" mapped to the function's arguments.
  • Make a POST request to the url assigning the payload as JSON.
  • Test the function works with the values provided.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

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)
Code bearbeiten und ausführen