{"record":{"id":"7c21850f70154b3f","repo":"python/cpython","slug":"fromutc-requires-a-datetime-argument","errorCode":null,"errorMessage":"fromutc() requires a datetime argument","messagePattern":"fromutc\\(\\) requires a datetime argument","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"Lib/_pydatetime.py","lineNumber":1335,"sourceCode":"        raise NotImplementedError(\"tzinfo subclass must override tzname()\")\n\n    def utcoffset(self, dt):\n        \"datetime -> timedelta, positive for east of UTC, negative for west of UTC\"\n        raise NotImplementedError(\"tzinfo subclass must override utcoffset()\")\n\n    def dst(self, dt):\n        \"\"\"datetime -> DST offset as timedelta, positive for east of UTC.\n\n        Return 0 if DST not in effect.  utcoffset() must include the DST\n        offset.\n        \"\"\"\n        raise NotImplementedError(\"tzinfo subclass must override dst()\")\n\n    def fromutc(self, dt):\n        \"datetime in UTC -> datetime in local time.\"\n\n        if not isinstance(dt, datetime):\n            raise TypeError(\"fromutc() requires a datetime argument\")\n        if dt.tzinfo is not self:\n            raise ValueError(\"dt.tzinfo is not self\")\n\n        dtoff = dt.utcoffset()\n        if dtoff is None:\n            raise ValueError(\"fromutc() requires a non-None utcoffset() \"\n                             \"result\")\n\n        # See the long comment block at the end of this file for an\n        # explanation of this algorithm.\n        dtdst = dt.dst()\n        if dtdst is None:\n            raise ValueError(\"fromutc() requires a non-None dst() result\")\n        delta = dtoff - dtdst\n        if delta:\n            dt += delta\n            dtdst = dt.dst()\n            if dtdst is None:","sourceCodeStart":1317,"sourceCodeEnd":1353,"githubUrl":"https://github.com/python/cpython/blob/bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6/Lib/_pydatetime.py#L1317-L1353","documentation":"Raised by tzinfo.fromutc() when its argument is not a datetime instance. fromutc(dt) converts a datetime expressing UTC time into local time under this tzinfo; the default implementation reads dt.utcoffset(), dt.dst() and dt.tzinfo, so it requires a real datetime. Passing a date, a time, a timestamp number, or a string triggers this TypeError.","triggerScenarios":"tz.fromutc(time(12,0)); tz.fromutc('2024-01-01T00:00:00'); tz.fromutc(date(2024,1,1)); tz.fromutc(1700000000); passing a pandas Timestamp subclass that fails isinstance in exotic cases.","commonSituations":"Wrapping fromutc in generic conversion utilities that accept multiple input types; confusing fromutc with datetime.fromtimestamp (which takes a number); feeding ISO strings directly instead of parsing them first.","solutions":["Parse the value to a datetime first: datetime.fromisoformat(s) before calling fromutc","If you have a POSIX timestamp, use datetime.fromtimestamp(ts, tz) — it applies fromutc internally","Ensure the datetime is UTC-based and has tzinfo set to this tzinfo object before calling"],"exampleFix":"// before\nlocal = tz.fromutc('2024-06-01T12:00:00+00:00')\n\n// after\nfrom datetime import datetime, timezone\ndt_utc = datetime.fromisoformat('2024-06-01T12:00:00+00:00').replace(tzinfo=tz)\nlocal = tz.fromutc(dt_utc)","handlingStrategy":"type-guard","validationCode":"if not isinstance(dt, datetime):\n    if isinstance(dt, str):\n        dt = datetime.fromisoformat(dt)\n    elif isinstance(dt, (int, float)):\n        dt = datetime.fromtimestamp(dt, timezone.utc)\n    else:\n        raise TypeError('fromutc needs a datetime')\ntz.fromutc(dt)","typeGuard":"from datetime import datetime as _dt\ndef is_datetime(v) -> bool:\n    return isinstance(v, _dt)","tryCatchPattern":"try:\n    local = tz.fromutc(dt)\nexcept TypeError:\n    local = tz.fromutc(datetime.fromisoformat(dt))  # after confirming the input type","preventionTips":["Always pass datetime objects to fromutc; parse strings/numbers beforehand","Wrap conversions in one utility that normalizes input types first","Prefer datetime.fromtimestamp(ts, tz) for numeric timestamps"],"tags":["datetime","timezone","typeerror","fromutc"],"backgroundTag":null,"analyzedSha":"bc6749cc3b5ae4a5e88a6cc2d5b3bebbe354eae6","analyzedAt":"2026-08-14T22:01:13.976Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}