Andromeda
Note

Datetime Module (Python)

Definition

A module for representing and manipulating specific moments in time (dates and hours) and durations.

Why It Matters

Time is one of the most complex dimensions in software due to the irregular rules of calendars and timezones. The datetime module provides the robust tools needed to manage these complexities, ensuring that scheduling and historical analysis are accurate.

Core Concepts

import datetime

# Current moment
now = datetime.datetime.now()

# Time arithmetic
tomorrow = now + datetime.timedelta(days=1)

# Formatting
print(now.strftime("%Y-%m-%d %H:%M:%S"))

# Parsing
dt = datetime.datetime.strptime("2026-06-15", "%Y-%m-%d")
  • datetime.datetime Objects: Represent a specific point in time (Year, Month, Day, Hour, Min, Sec). Use .now() for the current moment.
  • datetime.timedelta Objects: Represent a duration or difference between two moments. Allows for date arithmetic (e.g., future = now + delta).
  • Format vs. Parse (The ‘F’ and ‘P’ Rule):
    • strftime() (Format): Converts a datetime object into a formatted string.
    • strptime() (Parse): Parses a string into a datetime object.
  • Comparison: Datetime objects can be compared using standard operators (<, >, ==).

Connected Concepts