TauricResearch/TradingAgents · error · ValueError

Unsupported date format: {date_input}

Error message

Unsupported date format: {date_input}

What it means

Raised by format_datetime_for_api() in tradingagents/dataflows/alpha_vantage_common.py when a date string is neither already in the 13-char YYYYMMDDTHHMM form, nor parseable as '%Y-%m-%d', nor as '%Y-%m-%d %H:%M'. It is a plain ValueError (raised 'from None' so the underlying strptime error is suppressed). It exists to reject date strings the Alpha Vantage intraday API cannot accept before the request is made.

Source

Thrown at tradingagents/dataflows/alpha_vantage_common.py:52

        )
    return api_key

def format_datetime_for_api(date_input) -> str:
    """Convert various date formats to YYYYMMDDTHHMM format required by Alpha Vantage API."""
    if isinstance(date_input, str):
        # If already in correct format, return as-is
        if len(date_input) == 13 and 'T' in date_input:
            return date_input
        # Try to parse common date formats
        try:
            dt = datetime.strptime(date_input, "%Y-%m-%d")
            return dt.strftime("%Y%m%dT0000")
        except ValueError:
            try:
                dt = datetime.strptime(date_input, "%Y-%m-%d %H:%M")
                return dt.strftime("%Y%m%dT%H%M")
            except ValueError:
                raise ValueError(f"Unsupported date format: {date_input}") from None
    elif isinstance(date_input, datetime):
        return date_input.strftime("%Y%m%dT%H%M")
    else:
        raise ValueError(f"Date must be string or datetime object, got {type(date_input)}")

class AlphaVantageRateLimitError(VendorRateLimitError):
    """Raised when the Alpha Vantage API rate limit is exceeded."""
    pass

def _make_api_request(function_name: str, params: dict) -> dict | str:
    """Helper function to make API requests and handle responses.

    Raises:
        AlphaVantageRateLimitError: When API rate limit is exceeded
    """
    # Create a copy of params to avoid modifying the original
    api_params = params.copy()
    api_params.update({

View on GitHub (pinned to a33fd4c0f1)

Solutions

  1. Pass the date as a datetime.datetime object instead of a string — the function formats it correctly itself
  2. Use one of the accepted string forms: 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM', or the pre-formatted 'YYYYMMDDTHHMM'
  3. Normalize upstream: convert ISO strings with datetime.fromisoformat(s) (strip 'Z' first) before passing the datetime through
  4. Pre-validate with a helper that parses the common formats and re-emits '%Y-%m-%d' before calling the library

Example fix

# before
format_datetime_for_api("2025-01-15T10:30:00Z")
# -> ValueError: Unsupported date format: 2025-01-15T10:30:00Z

# after
from datetime import datetime
dt = datetime.fromisoformat("2025-01-15T10:30:00".replace("Z", "+00:00"))
format_datetime_for_api(dt)  # -> "20250115T1030"
Defensive patterns

Strategy: validation

Validate before calling

from datetime import datetime

def to_api_date(value: str) -> str:
    """Normalize common date strings to 'YYYY-MM-DD' the formatter accepts.""
    for fmt in ("%Y-%m-%d %H:%M", "%Y-%m-%d"):
        try:
            return datetime.strptime(value.strip(), fmt).strftime("%Y-%m-%d")
        except ValueError:
            continue
    dt = datetime.fromisoformat(value.replace("Z", "+00:00"))  # ISO-8601
    return dt.strftime("%Y-%m-%d")

Type guard

import re
from datetime import datetime

def is_acceptable_date(v) -> bool:
    if isinstance(v, datetime):
        return True
    return isinstance(v, str) and bool(
        re.fullmatch(r"\d{8}T\d{4}|\d{4}-\d{2}-\d{2}( \d{2}:\d{2})?", v.strip())
    )

Try / catch

try:
    ts = format_datetime_for_api(start)
except ValueError as e:
    raise ValueError(f"Fix the date input {start!r}: use 'YYYY-MM-DD' or a datetime") from e

Prevention

When it happens

Trigger: Passing dates like '2025/01/15', 'Jan 15 2025', '2025-01-15T10:30', ISO strings with seconds/timezone ('2025-01-15T10:30:00Z'), or strings with stray whitespace to any code path that formats datetimes for Alpha Vantage (e.g. intraday range endpoints).

Common situations: LLM tool calls emitting ISO-8601 timestamps; frontend code forwarding browser Date.toJSON() output; users typing slash-formatted dates; mixing datetime.isoformat() output with the expected format.

Related errors


AI-assisted analysis of TauricResearch/TradingAgents@a33fd4c0f1 (2026-08-14). Data as JSON: /api/errors/9cf53745124b1b15. Report an issue: GitHub.