Skip to main content

Standard Library

datetime, math & random

Complete lesson for datetime, math & random using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — datetime, math & random

Section: Standard Library. Use datetime, math, and random with reproducible seeds — fixed dates, not now(), for reliable tutorials and tests.

datetime module map

  • datetime.date — calendar date (year, month, day).
  • datetime.datetime — date plus time (and optional tzinfo).
  • datetime.time — time of day; datetime.timedelta — duration differences.
  • Build values explicitly for tutorials and tests — avoid datetime.now() so outputs stay stable.
import datetime as dt

day = dt.date(2026, 10, 25)
stamp = dt.datetime(2026, 10, 25, 14, 30, 0)
print(day, stamp)
print(stamp.date(), stamp.time())

Constructing dates safely

  • date(y, m, d) and datetime(y, m, d, H=0, M=0, S=0) validate ranges and raise ValueError on illegal dates.
  • date.fromisoformat('2026-10-25') parses ISO dates.
  • datetime.fromisoformat('2026-10-25T14:30:00') parses ISO datetimes.
  • Prefer ISO strings in data files; convert for display with strftime.
from datetime import date, datetime

print(date.fromisoformat("2026-10-25"))
print(datetime.fromisoformat("2026-10-25T09:15:00"))
print(date(2026, 2, 28))

timedelta arithmetic

  • timedelta(days=..., hours=..., minutes=..., seconds=...) adds/subtracts durations.
  • d2 - d1 yields a timedelta for dates or datetimes.
  • .days and .total_seconds() are the usual accessors.
  • timedelta does not include months — use dateutil.relativedelta (third party) or manual calendar logic for months.
from datetime import date, datetime, timedelta

start = date(2026, 10, 25)
print(start + timedelta(days=7))
print(start - timedelta(days=3))
a = datetime(2026, 10, 25, 10, 0, 0)
b = datetime(2026, 10, 25, 12, 30, 0)
delta = b - a
print(delta, delta.total_seconds())

Formatting and parsing

  • strftime(fmt) formats; strptime(text, fmt) parses.
  • Common tokens: %Y year, %m month, %d day, %H %M %S, %A weekday name.
  • Always match the format string to the input exactly.
  • ISO is safer for interchange; strftime is for human displays.
from datetime import datetime

stamp = datetime(2026, 10, 25, 16, 45, 0)
print(stamp.strftime("%Y-%m-%d %H:%M"))
print(stamp.strftime("%A, %d %B %Y"))
parsed = datetime.strptime("25/10/2026 16:45", "%d/%m/%Y %H:%M")
print(parsed)

math module essentials

  • import math for sqrt, ceil, floor, fabs, factorial, gcd, log, sin, pi, inf.
  • math.isclose(a, b) compares floats with tolerances.
  • math.prod multiplies iterables (3.8+); math.comb / math.perm for counting.
  • Integers use unlimited precision; use math for real-valued operations and combinatorics helpers.
import math

print(math.sqrt(49))
print(math.ceil(3.1), math.floor(3.9))
print(math.gcd(48, 18))
print(math.comb(5, 2))
print(math.isclose(0.1 + 0.2, 0.3))

random with seed — always

  • random.seed(n) makes the sequence reproducible — required in these lessons and tests.
  • random.random() → float in [0.0, 1.0); randrange, randint, choice, shuffle, sample.
  • Call seed once at the start of the program (or before each demo block) with a fixed integer.
  • Without a seed, demos differ every run — bad for tutorials and assertions.
import random

random.seed(42)
print(random.randint(1, 6))
print(random.choice(["red", "green", "blue"]))
nums = [1, 2, 3, 4, 5]
random.shuffle(nums)
print(nums)
print(random.sample(range(10), 3))

date calendars and weekdays

  • date.weekday() — Monday=0 … Sunday=6; isoweekday() — Monday=1 … Sunday=7.
  • date.replace(year=..., month=..., day=...) builds a modified copy.
  • datetime.min / datetime.max exist but prefer explicit teaching values.
  • Leap years: date(2024, 2, 29) works; date(2025, 2, 29) raises.
from datetime import date

d = date(2026, 10, 25)
print(d.weekday(), d.isoweekday(), d.strftime("%A"))
print(d.replace(day=1))
try:
    date(2025, 2, 29)
except ValueError as exc:
    print("invalid", exc)

Combining modules in tiny apps

  • Seed random, pick a practice quiz date with timedelta, round scores with math.
  • Keep wall-clock now() out of lesson programs so expected output stays fixed.
  • For “current time” product features, isolate now behind a function you can stub in tests.
  • Document the seed value in comments when sharing demos.
import math
import random
from datetime import date, timedelta

random.seed(7)
base = date(2026, 10, 25)
session = base + timedelta(days=random.randint(1, 5))
score = 17 / 3
print("session", session.isoformat())
print("rounded", round(score, 2), "ceil", math.ceil(score))

math vs operator vs built-ins

  • abs, round, min, max, pow are built-ins; math adds domain-specific helpers.
  • pow(x, y, mod) does modular exponentiation — useful in contests.
  • math.sqrt returns float; for integer square-root checks use math.isqrt (3.8+).
  • // is floor division for ints; combine with math carefully for negatives.
NeedUseExample
Integer sqrtmath.isqrtisqrt(10) == 3
Combinationsmath.combcomb(5, 2)
Float close?math.iscloseisclose(0.1+0.2, 0.3)
Seeded dicerandom + seedseed(42); randint(1, 6)

Timezone awareness (overview)

  • Naive datetimes have tzinfo is None; aware ones carry a zone.
  • stdlib zoneinfo.ZoneInfo (3.9+) attaches IANA names like Asia/Kolkata.
  • Still construct explicit base moments in lessons — do not call now().
  • Convert with .astimezone(ZoneInfo(...)) when teaching zones.
from datetime import datetime
from zoneinfo import ZoneInfo

naive = datetime(2026, 10, 25, 12, 0, 0)
aware = naive.replace(tzinfo=ZoneInfo("UTC"))
india = aware.astimezone(ZoneInfo("Asia/Kolkata"))
print(aware)
print(india)
L2

Advanced — datetime, math & random

Why tutorials ban datetime.now()

  • now() (and today()) make golden outputs drift by day and timezone.
  • CI snapshots and printed lesson keys would break overnight.
  • Inject a clock function in real apps: def get_clock(): return datetime.now() — swap in tests.
  • Here we always write datetime(2026, 10, 25, ...) or parse fixed ISO strings.

timedelta limits and dateutil

  • Adding timedelta(days=30) is not “plus one month”; months have different lengths.
  • End-of-month math needs calendar rules (calendar.monthrange).
  • date + timedelta works; adding timedelta to a bare time is not supported.
  • For business days, skip weekends explicitly in a loop.
import calendar
from datetime import date

def add_months(d, months):
    m0 = d.month - 1 + months
    y = d.year + m0 // 12
    m = m0 % 12 + 1
    last = calendar.monthrange(y, m)[1]
    day = min(d.day, last)
    return date(y, m, day)

print(add_months(date(2026, 1, 31), 1))
print(add_months(date(2026, 1, 31), 2))

random reproducibility details

  • seed(42) resets the algorithm state; same seed ⇒ same sequence for the same Python version’s algorithm.
  • Do not rely on exact sequences across major Python versions for crypto — use secrets for security.
  • random.Random(42) creates an isolated RNG instance — better than global state in libraries.
  • Shuffle is in-place; use sample when you need an unshuffled original list.
import random

rng = random.Random(42)
print([rng.randint(1, 10) for _ in range(5)])
rng2 = random.Random(42)
print([rng2.randint(1, 10) for _ in range(5)])

Floating math pitfalls

  • Binary floats cannot represent 0.1 exactly — use Decimal for currency.
  • math.fsum reduces summation error versus sum for many floats.
  • math.nan compares unequal to itself; use math.isnan.
  • round uses bankers rounding for .5 cases in Python 3 — know it for tests.
import math
from decimal import Decimal, ROUND_HALF_UP

print(0.1 + 0.2)
print(math.fsum([0.1] * 10))
print(Decimal("10.005").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))

calendar and time modules

  • calendar.monthrange(year, month) → (weekday_of_first, days_in_month).
  • calendar.isleap(year) checks leap years.
  • time.sleep pauses; time.perf_counter measures intervals — separate from datetime clocks.
  • Do not confuse time.time() epoch seconds with datetime objects without conversion.
import calendar

print(calendar.isleap(2024), calendar.isleap(2025))
print(calendar.monthrange(2026, 2))
print(calendar.day_name[0])

strftime locale and UTC

  • Weekday/month names follow locale settings — prefer numeric ISO for machine data.
  • %z / %Z need aware datetimes.
  • Store UTC in databases; convert to local zones only at the edges.
  • Parsing ambiguous local times around DST needs zone libraries and rules.

Combinatorics and number helpers

  • math.comb(n, k) = n choose k; math.perm(n, k) permutations.
  • math.lcm (3.9+) and math.gcd for multiple integers via functools.reduce historically.
  • math.dist(p, q) Euclidean distance between iterables.
  • Factorial grows fast — prefer comb/perm to avoid huge intermediates when possible.
import math

print(math.perm(5, 2), math.comb(5, 2))
print(math.lcm(4, 6))
print(math.dist((0, 0), (3, 4)))

Secrets vs random

  • random is for simulations and games — not passwords or tokens.
  • secrets.token_hex, secrets.randbelow are for security-sensitive values.
  • Lesson programs still use random.seed for demos of games and sampling.
  • Never seed with datetime.now() — that reintroduces non-determinism.
L3

Tricky Interview Points

Q1) How do you create a fixed datetime?

Answer Call datetime.datetime(year, month, day, hour, minute, second) or datetime.fromisoformat with a fixed string.

Q2) Why avoid datetime.now() in tutorials?

Answer It changes every run and breaks expected output, snapshots, and grading.

Q3) What is timedelta?

Answer A duration used to add/subtract time from dates or datetimes, or as the result of subtracting two datetimes.

Q4) strftime vs strptime?

Answer strftime formats a datetime into a string; strptime parses a string into a datetime using a format.

Q5) How do you make random reproducible?

Answer Call random.seed(fixed_int) before drawing values, or use random.Random(seed).

Q6) randint vs randrange?

Answer randint(a, b) includes both endpoints. randrange(a, b) is like range — stop is exclusive.

Q7) math.isclose purpose?

Answer Compares floats with relative/absolute tolerance instead of fragile ==.

Q8) How to get day of week?

Answer date.weekday() (Mon=0) or isoweekday() (Mon=1), or strftime('%A').

Q9) Does timedelta support months?

Answer No. Use calendar arithmetic or a library such as dateutil.relativedelta.

Q10) math.isqrt vs int(math.sqrt(n))?

Answer isqrt returns the integer square root exactly for ints; float sqrt can mis-round large ints.

Q11) When use secrets instead of random?

Answer For passwords, tokens, OTP-style values — anything security-sensitive.

Q12) What does random.sample do?

Answer Returns k distinct elements from a population without modifying it.

Q13) Naive vs aware datetime?

Answer Naive has tzinfo=None. Aware includes timezone info (e.g. ZoneInfo).

Q14) How to parse ISO dates?

Answer date.fromisoformat or datetime.fromisoformat for standard ISO-8601 strings.

Q15) Why seed(42) at the top?

Answer So every run of the lesson program prints the same random sequence.

L4

Simple Programs

Fixed deadline countdown

from datetime import date, timedelta

assigned = date(2026, 10, 25)
due = assigned + timedelta(days=10)
print("assigned", assigned.isoformat())
print("due", due.isoformat())
print("days allowed", (due - assigned).days)
milestones = [assigned + timedelta(days=d) for d in (3, 7, 10)]
for m in milestones:
    print("milestone", m.strftime("%A %d %b"))

Seeded dice statistics

import random
from collections import Counter

random.seed(42)
rolls = [random.randint(1, 6) for _ in range(60)]
print(Counter(rolls))
print("first five", rolls[:5])

math helpers cheat sheet run

import math

values = [3.2, 3.8, -1.1]
for v in values:
    print(v, "floor", math.floor(v), "ceil", math.ceil(v), "trunc", math.trunc(v))
print("gcd", math.gcd(84, 30))
print("comb", math.comb(10, 3))
print("isclose", math.isclose(1.0, 0.1 * 10))

strftime report lines

from datetime import datetime

events = [
    datetime(2026, 10, 25, 9, 0, 0),
    datetime(2026, 10, 25, 13, 30, 0),
    datetime(2026, 10, 26, 11, 15, 0),
]
for e in events:
    print(e.strftime("%Y-%m-%d %H:%M (%A)"))

Isolated RNG instances

import random

a = random.Random(1)
b = random.Random(1)
c = random.Random(2)
print([a.random() for _ in range(3)])
print([b.random() for _ in range(3)])
print([c.random() for _ in range(3)])

Business days adder

from datetime import date, timedelta

def add_business_days(start, n):
    d = start
    added = 0
    while added < n:
        d += timedelta(days=1)
        if d.weekday() < 5:
            added += 1
    return d

start = date(2026, 10, 23)  # Friday
print(add_business_days(start, 1))  # Monday
print(add_business_days(start, 5))

Seeded sample quiz picker

import math
import random
from datetime import date

random.seed(99)
bank = ["lists", "dicts", "loops", "functions", "oop", "modules"]
picks = random.sample(bank, 3)
quiz_day = date(2026, 11, 1)
print("quiz on", quiz_day.isoformat())
print("topics", picks)
print("score cap", math.comb(len(bank), 3))
L5

Problem Solving Tricks

  • Construct date/datetime with literals — skip now() / today() in lesson code.
  • Always random.seed(...) (or Random(seed)) before random draws in demos.
  • ISO for storage: date.isoformat(); pretty print with strftime.
  • timedelta has no months — use calendar logic for month math.
  • math.isclose for float compares; Decimal for money.
  • math.isqrt for integer square roots.
  • Use random.sample to pick without replacement; choice for one item.
  • Random(seed) isolates streams when modules share global random.
  • Never seed with the clock if you want reproducibility.
  • secrets for tokens; random for games and simulations.
L6

Practice Programs List

  1. Create a study plan of 5 dates starting 2026-10-25 every 3 days.
  2. Parse '25-10-2026' with strptime and reprint with strftime.
  3. Seed 42 and simulate 100 coin flips; count heads/tails.
  4. Write add_months using calendar.monthrange.
  5. Compare sum vs math.fsum on many 0.1 values.
  6. Build aware UTC datetime and convert to Asia/Kolkata.
  7. Use math.comb to compute lottery odds for small n/k.
  8. Implement a seeded shuffle of a deck of 8 cards.
  9. Compute business-day difference between two fixed dates.
  10. Show why 0.1 + 0.2 != 0.3 and fix with Decimal.
  11. Rewrite a script that used now() to use a fixed datetime.
  12. Create two Random instances with different seeds and print sequences.