datetime, timedelta, & TimezonesPython's built-in datetime module provides classes for parsing, manipulating, formatting, and arithmetic operations on dates, times, and timezones.
flowchart TD
A["datetime Module"] --> B["date (year, month, day)"]
A --> C["time (hour, minute, second, microsecond)"]
A --> D["datetime (combined date & time)"]
A --> E["timedelta (duration / difference)"]
A --> F["zoneinfo.ZoneInfo (IANNA Timezone)"]
datetime.now(tz): Retrieve current local or timezone-aware datetime.datetime.strptime(date_str, format): Parse string into a datetime object.datetime.strftime(format): Format a datetime object into a formatted string.timedelta(days=..., hours=...): Represent time intervals for date arithmetic.from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
def datetime_operations_demo() -> None:
# Timezone-aware UTC timestamp
utc_now = datetime.now(timezone.utc)
print(f"Current UTC Time: {utc_now.isoformat()}")
# Date Arithmetic with timedelta
one_week_later = utc_now + timedelta(days=7)
print(f"1 Week from Now: {one_week_later.strftime('%Y-%m-%d %H:%M:%S %Z')}")
# ISO 8601 Parsing & Formatting
iso_string = "2026-08-15T14:30:00+00:00"
parsed_dt = datetime.fromisoformat(iso_string)
print(f"Parsed ISO String -> Month: {parsed_dt.strftime('%B')}, Day: {parsed_dt.day}")
# Convert to specific timezone (e.g. America/New_York)
ny_tz = ZoneInfo("America/New_York")
ny_dt = utc_now.astimezone(ny_tz)
print(f"New York Local Time: {ny_dt.strftime('%Y-%m-%d %I:%M %p %Z')}")
if __name__ == "__main__":
datetime_operations_demo()
datetime.now(timezone.utc).fromisoformat(): In Python 3.11+, datetime.fromisoformat() parses almost all standard ISO 8601 strings automatically without needing explicit strptime() format specifiers.Write a function days_until(target_date_str: str) -> int that parses "YYYY-MM-DD" and calculates the number of remaining days from today.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With