[{"data":1,"prerenderedAt":67},["ShallowReactive",2],{"qa-\u002Fpython\u002Fstdlib\u002Fdatetime":3},{"page":4,"siblings":54,"blog":45},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"related":45,"seo":46,"seoDescription":47,"stem":48,"subtopic":49,"topic":50,"topicSlug":51,"updated":52,"__hash__":53},"qa\u002Fpython\u002Fstdlib\u002Fdatetime.md","Datetime",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Python","python",{},true,3,"\u002Fpython\u002Fstdlib\u002Fdatetime",[23,28,33,37,41],{"id":24,"difficulty":25,"q":26,"a":27},"datetime-date-time","easy","What is the difference between datetime, date, and time?","The `datetime` module provides three core types. **`date`** holds a calendar date\n(year, month, day) with **no time**. **`time`** holds a time of day (hour, minute,\nsecond, microsecond) with **no date**. **`datetime`** combines **both** into a\nsingle timestamp.\n\n```python\nfrom datetime import date, time, datetime\n\nd = date(2026, 6, 18)               # just the date\nt = time(14, 30, 0)                 # just the time of day\ndt = datetime(2026, 6, 18, 14, 30)  # date + time together\n\ndt.date()                           # -> date(2026, 6, 18)\ndt.time()                           # -> time(14, 30)\ndate.today()                        # current date\n```\n\nUse `date` for things like birthdays or due dates where time is irrelevant, `time`\nfor a recurring clock time, and `datetime` for actual events\u002Ftimestamps. Most\nreal-world work uses `datetime`.\n",{"id":29,"difficulty":30,"q":31,"a":32},"naive-aware-zoneinfo","hard","What is the difference between naive and timezone-aware datetimes?","A **naive** datetime has **no timezone info** (`tzinfo` is `None`) — it's just wall\nclock numbers with no reference point, so it's ambiguous. An **aware** datetime\ncarries a `tzinfo`, pinning it to an actual instant. Use the stdlib **`zoneinfo`**\nmodule (Python 3.9+) to attach real IANA timezones.\n\n```python\nfrom datetime import datetime\nfrom zoneinfo import ZoneInfo\n\nnaive = datetime(2026, 6, 18, 14, 30)          # ambiguous — no tz\naware = datetime(2026, 6, 18, 14, 30,\n                 tzinfo=ZoneInfo(\"America\u002FNew_York\"))\n\nutc = aware.astimezone(ZoneInfo(\"UTC\"))        # convert between zones\n```\n\nYou **can't compare or subtract** a naive and an aware datetime — it raises\n`TypeError`. Best practice: store and compute in **UTC-aware** datetimes, and convert\nto local zones only for display.\n",{"id":34,"difficulty":14,"q":35,"a":36},"strftime-strptime","What is the difference between strftime and strptime?","They are inverses. **`strftime`** (\"string **f**rom time\") **formats** a datetime\n**into** a string using format codes. **`strptime`** (\"string **p**arse time\")\n**parses** a string **into** a datetime using a matching format.\n\n```python\nfrom datetime import datetime\n\ndt = datetime(2026, 6, 18, 14, 30)\ns = dt.strftime(\"%Y-%m-%d %H:%M\")       # datetime -> \"2026-06-18 14:30\"\n\nparsed = datetime.strptime(\"2026-06-18 14:30\",\n                           \"%Y-%m-%d %H:%M\")  # str -> datetime\n```\n\nCommon codes: `%Y` (4-digit year), `%m` (month), `%d` (day), `%H` (24-hour),\n`%M` (minute), `%S` (second). To remember: **f** = format (out), **p** = parse (in).\nFor standard ISO strings, `datetime.fromisoformat()` \u002F `.isoformat()` are simpler.\n",{"id":38,"difficulty":14,"q":39,"a":40},"timedelta-arithmetic","How does timedelta arithmetic work?","A **`timedelta`** represents a **duration** — a difference between two points in time.\nSubtracting two datetimes yields a `timedelta`; adding a `timedelta` to a datetime\nshifts it. A `timedelta` stores days, seconds, and microseconds.\n\n```python\nfrom datetime import datetime, timedelta\n\nstart = datetime(2026, 6, 18, 9, 0)\nend   = datetime(2026, 6, 18, 17, 30)\n\nworked = end - start              # timedelta(seconds=30600)\nworked.total_seconds()            # 30600.0\nworked.seconds \u002F\u002F 3600            # 8 (hours portion)\n\ntomorrow = start + timedelta(days=1)      # shift forward\nweek_ago = start - timedelta(weeks=1)     # shift back\n```\n\nUse `total_seconds()` to get the whole duration as a number (the `.seconds`\nattribute is only the sub-day part). `timedelta` makes date math safe — it correctly\nrolls over months and years.\n",{"id":42,"difficulty":30,"q":43,"a":44},"now-vs-utcnow","What is the pitfall with datetime.now() vs utcnow()?","The big trap: **both `datetime.now()` and the old `datetime.utcnow()` return *naive*\ndatetimes**. `now()` gives local wall time, `utcnow()` gives the UTC wall time — but\n**neither attaches a tzinfo**, so a `utcnow()` value silently *looks* like local\ntime and corrupts later conversions. `utcnow()` is **deprecated** in modern Python.\n\n```python\nfrom datetime import datetime\nfrom zoneinfo import ZoneInfo\n\ndatetime.now()                       # naive, local time — ambiguous\ndatetime.utcnow()                    # naive, but labelled nothing! (deprecated)\n\n# correct: an AWARE UTC timestamp\nnow_utc = datetime.now(ZoneInfo(\"UTC\"))\nlocal = datetime.now(ZoneInfo(\"America\u002FNew_York\"))\n```\n\nRule of thumb: **always pass a timezone to `now()`** to get an aware datetime, and\navoid `utcnow()` entirely. Store timestamps as UTC-aware and convert for display.\n",null,{"description":11},"Python interview questions on datetime vs date vs time, naive vs timezone-aware datetimes with zoneinfo, strftime\u002Fstrptime, timedelta arithmetic, and the now() vs utcnow() pitfall.","python\u002Fstdlib\u002Fdatetime","datetime","Standard Library Essentials","stdlib","2026-06-18","5GeL0A_Cp3gxfR8_dMsYRrPzndiAo9KQrpPZqTy-QDE",[55,59,62,63],{"subtopic":56,"path":57,"order":58},"Regular Expressions","\u002Fpython\u002Fstdlib\u002Fregex",1,{"subtopic":60,"path":61,"order":12},"Files, pathlib & os","\u002Fpython\u002Fstdlib\u002Ffiles-pathlib",{"subtopic":49,"path":21,"order":20},{"subtopic":64,"path":65,"order":66},"JSON, CSV & pickle","\u002Fpython\u002Fstdlib\u002Fserialization",4,1781808681916]