CodeNebula
Python📦Standard Libraryintermediate

`datetime` — Dates, Times, and Timezones

Python · Standard Library · Run with python3

Explanation

The `datetime` module provides `date`, `time`, `datetime`, `timedelta`, and `timezone`. `datetime.now()` returns local time (tz-naive); `datetime.now(timezone.utc)` returns UTC-aware. Always store timestamps as UTC; convert to local time at display. `timedelta` supports arithmetic. Python 3.9+ added `zoneinfo` for IANA timezone database (e.g., `"America/New_York"`).

Real-World Scenario

A scheduler must fire a job "every Monday at 9 AM New York time". Storing the next-run time as UTC in the database, then converting to New York time for display, avoids daylight-saving bugs. `timedelta(weeks=1)` gives the repeat interval. ```python from datetime import datetime, timedelta, timezone from zoneinfo import ZoneInfo # Python 3.9+ # Always use aware datetimes in applications utc_now = datetime.now(timezone.utc) ny_tz = ZoneInfo("America/New_York") ny_time = utc_now.astimezone(ny_tz) print(f"UTC: {utc_now.isoformat()}") print(f"New York: {ny_time.strftime('%Y-%m-%d %H:%M %Z')}") # Arithmetic deadline = datetime(2024, 12, 31, tzinfo=timezone.utc) remaining = deadline - utc_now print(f"Days until deadline: {remaining.days}") # Parsing event_str = "2024-03-15T10:30:00Z" event_dt = datetime.fromisoformat(event_str.replace("Z", "+00:00")) print(f"Event: {event_dt}") ```

Quick Snippet

snippet.py
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo  # Python 3.9+

# Always use aware datetimes in applications
utc_now = datetime.now(timezone.utc)
ny_tz   = ZoneInfo("America/New_York")
ny_time = utc_now.astimezone(ny_tz)

print(f"UTC:      {utc_now.isoformat()}")
print(f"New York: {ny_time.strftime('%Y-%m-%d %H:%M %Z')}")

# Arithmetic
deadline = datetime(2024, 12, 31, tzinfo=timezone.utc)
remaining = deadline - utc_now
print(f"Days until deadline: {remaining.days}")

# Parsing
event_str = "2024-03-15T10:30:00Z"
event_dt  = datetime.fromisoformat(event_str.replace("Z", "+00:00"))
print(f"Event: {event_dt}")

Full Example

datetime_basics.py
# Compile: python3 datetime_basics.py
# Output:
# UTC and New York times printed

from datetime import datetime, timedelta, timezone

try:
    from zoneinfo import ZoneInfo
    ny_tz = ZoneInfo("America/New_York")
    has_zoneinfo = True
except Exception:
    has_zoneinfo = False

utc_now = datetime.now(timezone.utc)
print(f"UTC: {utc_now.strftime('%Y-%m-%d %H:%M:%S %Z')}")

if has_zoneinfo:
    ny_time = utc_now.astimezone(ny_tz)
    print(f"New York: {ny_time.strftime('%Y-%m-%d %H:%M %Z')}")

# Arithmetic
deadline = datetime(2025, 12, 31, tzinfo=timezone.utc)
remaining = deadline - utc_now
print(f"Days until 2025-12-31: {remaining.days}")

one_week = timedelta(weeks=1)
next_week = utc_now + one_week
print(f"Next week: {next_week.strftime('%Y-%m-%d')}")

# Parsing ISO format
event_str = "2024-03-15T10:30:00+00:00"
event_dt  = datetime.fromisoformat(event_str)
print(f"Parsed: {event_dt}")

# strptime
dt = datetime.strptime("15/03/2024 10:30", "%d/%m/%Y %H:%M")
print(f"strptime: {dt}")
Run command
python3 datetime_basics.py