MOD-23 · Sequence #23 · Standard Library

Python Dates & Math

Python includes powerful batteries-included libraries: `math` for floating-point mathematical functions, and `datetime` for date, time, and timedelta calculations. Mastering ISO parsing and strftime formatting is essential for data processing.

Live Interactive Code Snippet (Python 3.12 CPython WASM) Open in Practice Mode →
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d"))

Core Principles & Mental Models

1. The math Module

Trigonometry, Logarithms, Constants

  • Provides C-standard mathematical functions: `math.sqrt`, `math.pow`, `math.sin`, `math.cos`, `math.log`, `math.gcd`.
  • Rounding utilities: `math.floor` (rounds down to -∞), `math.ceil` (rounds up to +∞), `math.trunc` (truncates decimals toward zero).
  • Mathematical constants: `math.pi`, `math.e`, `math.inf`, `math.nan`.
import math
print("math.ceil(4.1):", math.ceil(4.1))    # 5
print("math.floor(4.9):", math.floor(4.9))  # 4
print("math.gcd(24, 36):", math.gcd(24, 36)) # 12
💡 Key Takeaway: Use math functions for high-speed floating point computations.

2. The datetime and timedelta Objects

Date Arithmetic and String Formatting

  • `datetime.date` (year, month, day) and `datetime.datetime` (includes hours, minutes, seconds).
  • `datetime.timedelta` represents durations between two dates and enables arithmetic: `future = now + timedelta(days=7)`.
  • `strftime()` converts dates to formatted strings (%Y, %m, %d, %H, %M, %S).
  • `strptime()` parses strings into datetime objects.
import datetime
start = datetime.date(2026, 1, 1)
duration = datetime.timedelta(days=45)
end = start + duration
print("Calculated date:", end.strftime("%B %d, %Y"))
💡 Key Takeaway: Use timedelta objects for calendar arithmetic to correctly account for leap years and month lengths.

Interactive Walkthrough Examples

Parsing and Formatting Dates with strptime/strftime (Basic)

Converting raw log timestamps into formatted human-readable strings.

from datetime import datetime
raw_timestamp = "2026-10-08 14:30:00"
dt = datetime.strptime(raw_timestamp, "%Y-%m-%d %H:%M:%S")
formatted = dt.strftime("%A, %d %b %Y at %I:%M %p")
print("Formatted date:", formatted)

Explanation: strptime parses string -> datetime; strftime formats datetime -> string.

Common Misconceptions & Exam Traps

Common Pitfall: Confusing `strftime` (Format) and `strptime` (Parse)

strftime formats datetime objects into strings; strptime parses strings into datetime objects.

Buggy Code
# Trying to parse with strftime:
# dt = datetime.strftime("2026-01-01", "%Y-%m-%d") -> TypeError!
Correct Solution
from datetime import datetime
# Memory tip: 'f' = Format (to string), 'p' = Parse (from string)
dt = datetime.strptime("2026-01-01", "%Y-%m-%d")

Exam Trap Note: Remember: strftime = "string Format time", strptime = "string Parse time".

Conceptual Knowledge Self-Check Quiz

Q1: Which method parses a string timestamp into a Python datetime object?

  1. datetime.strftime()
  2. datetime.strptime()
  3. datetime.parse()
  4. datetime.from_string()

`datetime.strptime()` (Parse) converts string data into datetime objects.

Algorithmic Practice Challenges

Idiomatic Best Practices

  • ✅ Store dates in ISO 8601 format (YYYY-MM-DDTHH:MM:SS) for consistent database interoperability.
  • ✅ Always consider timezone awareness (timezone.utc) in distributed systems.

All 26 Curriculum Modules