{"record":{"id":"a4937dc4140f883d","repo":"TauricResearch/TradingAgents","slug":"date-must-be-string-or-datetime-object-got-type","errorCode":null,"errorMessage":"Date must be string or datetime object, got {type(date_input)}","messagePattern":"Date must be string or datetime object, got (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"tradingagents/dataflows/alpha_vantage_common.py","lineNumber":56,"sourceCode":"    \"\"\"Convert various date formats to YYYYMMDDTHHMM format required by Alpha Vantage API.\"\"\"\n    if isinstance(date_input, str):\n        # If already in correct format, return as-is\n        if len(date_input) == 13 and 'T' in date_input:\n            return date_input\n        # Try to parse common date formats\n        try:\n            dt = datetime.strptime(date_input, \"%Y-%m-%d\")\n            return dt.strftime(\"%Y%m%dT0000\")\n        except ValueError:\n            try:\n                dt = datetime.strptime(date_input, \"%Y-%m-%d %H:%M\")\n                return dt.strftime(\"%Y%m%dT%H%M\")\n            except ValueError:\n                raise ValueError(f\"Unsupported date format: {date_input}\") from None\n    elif isinstance(date_input, datetime):\n        return date_input.strftime(\"%Y%m%dT%H%M\")\n    else:\n        raise ValueError(f\"Date must be string or datetime object, got {type(date_input)}\")\n\nclass AlphaVantageRateLimitError(VendorRateLimitError):\n    \"\"\"Raised when the Alpha Vantage API rate limit is exceeded.\"\"\"\n    pass\n\ndef _make_api_request(function_name: str, params: dict) -> dict | str:\n    \"\"\"Helper function to make API requests and handle responses.\n\n    Raises:\n        AlphaVantageRateLimitError: When API rate limit is exceeded\n    \"\"\"\n    # Create a copy of params to avoid modifying the original\n    api_params = params.copy()\n    api_params.update({\n        \"function\": function_name,\n        \"apikey\": get_api_key(),\n        \"source\": \"trading_agents\",\n    })","sourceCodeStart":38,"sourceCodeEnd":74,"githubUrl":"https://github.com/TauricResearch/TradingAgents/blob/a33fd4c0f134485a43553a2c23a63cb14adbd88f/tradingagents/dataflows/alpha_vantage_common.py#L38-L74","documentation":"Raised by format_datetime_for_api() in tradingagents/dataflows/alpha_vantage_common.py when date_input is neither a str nor a datetime.datetime instance (e.g. a date, int, pandas.Timestamp-backed object, or None). It is a type-guard ValueError that fails fast before a malformed value reaches the Alpha Vantage URL builder.","triggerScenarios":"Passing datetime.date (not datetime), a Unix epoch integer, None, or a pandas Timestamp that does not pass isinstance(x, datetime) to a date parameter consumed by this formatter.","commonSituations":"Calling with datetime.date.today() instead of datetime.datetime.now(); passing an epoch int from a data pipeline; passing a timezone/untyped value deserialized from JSON; forwarding None when a field is optional in the caller's schema.","solutions":["Pass a datetime.datetime (convert dates with datetime.datetime.combine(d, datetime.time()) or datetime.datetime(d.year, d.month, d.day))","Pass a plain 'YYYY-MM-DD' string, which the function parses itself","Add an isinstance check or default in your caller so None/ints never reach this parameter"],"exampleFix":"# before\nformat_datetime_for_api(datetime.date(2025, 1, 15))\n# -> ValueError: Date must be string or datetime object, got <class 'datetime.date'>\n\n# after\nfrom datetime import datetime, date, time\nformat_datetime_for_api(datetime.combine(date(2025, 1, 15), time()))  # datetime.datetime passes\n# or simply\nformat_datetime_for_api(\"2025-01-15\")","handlingStrategy":"type-guard","validationCode":"from datetime import datetime, date\n\ndef coerce_date_input(value):\n    \"\"\"Return str/datetime or raise before the library does.\"\"\"\n    if isinstance(value, datetime):\n        return value\n    if isinstance(value, date):  # datetime.date -> midnight datetime\n        return datetime(value.year, value.month, value.day)\n    if isinstance(value, str) and value.strip():\n        return value.strip()\n    raise TypeError(f\"date must be str or datetime, got {type(value).__name__}\")","typeGuard":"from datetime import datetime\n\ndef is_str_or_datetime(v) -> bool:\n    return isinstance(v, (str, datetime)) and not (isinstance(v, str) and not v)","tryCatchPattern":"try:\n    format_datetime_for_api(d)\nexcept ValueError as e:\n    if \"must be string or datetime\" in str(e):\n        d = coerce_date_input(d)  # repair and retry once\n    else:\n        raise","preventionTips":["Type-annotate date parameters (str | datetime) and run mypy/pyright to catch date-vs-datetime mixups","Never forward None from optional schemas into date fields; resolve optionality at the caller","Watch out for datetime.date objects from DB rows — convert with datetime.combine"],"tags":["validation","type-error","date-format","alpha-vantage"],"backgroundTag":null,"analyzedSha":"a33fd4c0f134485a43553a2c23a63cb14adbd88f","analyzedAt":"2026-08-14T19:45:16.920Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}