How do you extract a date object from a Python datetime object? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you extract a date object from a Python datetime object?

message-square
0

Call the .date() method on a datetime.datetime instance (dt.date()) to extract a datetime.date object (containing only year, month, and day with time and timezone components stripped), or use pd.to_datetime(s).dt.date / .dt.floor("D") when extracting dates across a Pandas Series.

Basic Example

from datetime import datetime, timezone

# 1. Recommended: Call .date() on any datetime object
dt = datetime(2026, 11, 29, 14, 35, 10)
d = dt.date()

print(d)            # Output: 2026-11-29
print(type(d))      # Output: <class 'datetime.date'>

# 2. Timezone-aware datetime (convert to target timezone BEFORE calling .date()!):
utc_dt = datetime(2026, 11, 29, 22, 30, tzinfo=timezone.utc)
print(utc_dt.date())  # Output: 2026-11-29

Key Details & Edge Cases

  • datetime is a subclass of date (isinstance(dt, date) is True!), yet dt == d is False:
    • Because datetime.datetime inherits from datetime.date, isinstance(datetime.now(), date) evaluates to True, which can hide bugs if you pass a datetime into a function expecting a date.
    • Crucially, comparing a datetime directly to a date (datetime(2026, 11, 29, 0, 0) == date(2026, 11, 29)) always returns False, and dt < d raises TypeError: can't compare datetime.datetime to datetime.date. Always call .date() on both sides before comparing.
  • Timezone caveat: .date() drops tzinfo without converting:
    • dt.date() extracts the calendar date in dt’s current timezone (2026-11-29 22:30 UTC $\rightarrow$ 2026-11-29, even though at the same instant in PKT +05:00 it is already 2026-11-30 03:30). Convert to the user’s local timezone first (dt.astimezone(ZoneInfo("Asia/Karachi")).date()) before calling .date().
  • Calling .date() on an object that is already a datetime.date raises AttributeError:
    • date(2026, 11, 29).date() fails with AttributeError: 'datetime.date' object has no attribute 'date'. If an input might be either date or datetime, normalize safely with val.date() if isinstance(val, datetime) else val.
  • Pandas Series / DataFrame column (s.dt.date vs. s.dt.normalize() / s.dt.floor("D")):
    • df["ts"].dt.date produces an object-dtype Series of Python datetime.date instances (slower for downstream Pandas date arithmetic and grouping). When staying inside Pandas, prefer df["ts"].dt.floor("D") (or .dt.normalize()), which sets the time to 00:00:00 while preserving fast native datetime64[ns] vectorization.

Comparison of Date-Extraction Methods in Python & Pandas

Method Input Type Return Type Preserves Vectorized datetime64? Best Used When
dt.date() (Recommended) datetime.datetime datetime.date N/A (scalar Python object) Extracting a standard date object for dictionary keys, SQL parameters, or date comparisons.
dt.astimezone(tz).date() Aware datetime.datetime datetime.date N/A (scalar Python object) Getting the local calendar date in a specific timezone from a UTC timestamp.
s.dt.date Pandas datetime64 Series pd.Series (object dtype) No (stores Python date objects) Exporting pure datetime.date objects to CSV/JSON or passing to external Python APIs.
s.dt.floor("D") / s.dt.normalize() Pandas datetime64 Series pd.Series (datetime64[ns]) Yes (midnight 00:00:00 timestamps) Grouping, filtering, or joining by calendar day inside Pandas at full C/Arrow speed.