How do you get today's date formatted as YYYY-MM-DD in Python? | A1Lab@MZeeshanM to PythonEnglish • 5 days ago

How do you get today's date formatted as YYYY-MM-DD in Python?

message-square
0

Use datetime.date.today().isoformat() (or datetime.date.today().strftime("%Y-%m-%d")) for the local date, or datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d") when you need the current date in UTC.

Basic Example

from datetime import date, datetime, timezone

# 1. Recommended (cleanest): date.today().isoformat() defaults to YYYY-MM-DD
today_iso = date.today().isoformat()
print(today_iso)  # Output: "2026-11-27"

# 2. Explicit format string via strftime() or f-string formatting
today_str = date.today().strftime("%Y-%m-%d")
today_fstr = f"{date.today():%Y-%m-%d}"

# 3. Timezone-aware UTC date (recommended for servers, logs, and APIs)
utc_today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
print(utc_today)

Key Details & Edge Cases

  • date.today() vs. datetime.now(): Both date.today().isoformat() and datetime.now().strftime("%Y-%m-%d") return the machine’s local calendar date. If you already have a datetime object, .isoformat() includes the time ("2026-11-27T22:35:00.123456"), so call .date().isoformat() or .strftime("%Y-%m-%d") to get the date portion only.
  • Zero-padding behavior of %Y-%m-%d: %Y outputs a 4-digit year (2026), %m outputs a zero-padded 2-digit month (01–12), and %d outputs a zero-padded 2-digit day (01–31). Use lowercase %y only if you want a 2-digit year (26).
  • Avoid deprecated datetime.utcnow(): datetime.utcnow() is deprecated in Python 3.12+ because it returns a naive datetime lacking timezone metadata. Always use datetime.now(timezone.utc) or zoneinfo.ZoneInfo("America/New_York") for timezone-specific dates.
  • Alternative separators or compact formats: Swap hyphens in .strftime() when generating filenames or compact timestamps (e.g., date.today().strftime("%Y_%m_%d") $\rightarrow$ "2026_11_27" or date.today().strftime("%Y%m%d") $\rightarrow$ "20261127").

Comparison of Date Formatting Methods in Python

Method Syntax Timezone Return Type Best Used When
date.today().isoformat() date.today().isoformat() System local str ("YYYY-MM-DD") Getting today’s local ISO-8601 date with minimal boilerplate.
date.today().strftime(...) date.today().strftime("%Y-%m-%d") System local str Customizing separators (%Y_%m_%d, %Y/%m/%d) or formats.
f-string Format Specifier f"{date.today():%Y-%m-%d}" System local str Embedding formatted dates directly inside filenames, URLs, or log messages.
datetime.now(timezone.utc) datetime.now(timezone.utc).strftime("%Y-%m-%d") UTC str Cloud backends, databases, or distributed systems needing UTC consistency.