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.
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)anddatetime(y, m, d, H=0, M=0, S=0)validate ranges and raiseValueErroron 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 - d1yields a timedelta for dates or datetimes..daysand.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:
%Yyear,%mmonth,%dday,%H%M%S,%Aweekday 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 mathforsqrt,ceil,floor,fabs,factorial,gcd,log,sin,pi,inf.math.isclose(a, b)compares floats with tolerances.math.prodmultiplies iterables (3.8+);math.comb/math.permfor 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
seedonce 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.maxexist 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
nowbehind 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,poware built-ins;mathadds domain-specific helpers.pow(x, y, mod)does modular exponentiation — useful in contests.math.sqrtreturns float; for integer square-root checks usemath.isqrt(3.8+).//is floor division for ints; combine withmathcarefully for negatives.
| Need | Use | Example |
|---|---|---|
| Integer sqrt | math.isqrt | isqrt(10) == 3 |
| Combinations | math.comb | comb(5, 2) |
| Float close? | math.isclose | isclose(0.1+0.2, 0.3) |
| Seeded dice | random + seed | seed(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 likeAsia/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) Advanced — datetime, math & random
Why tutorials ban datetime.now()
now()(andtoday()) 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 + timedeltaworks; adding timedelta to a baretimeis 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
secretsfor security. random.Random(42)creates an isolated RNG instance — better than global state in libraries.- Shuffle is in-place; use
samplewhen 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
Decimalfor currency. math.fsumreduces summation error versussumfor many floats.math.nancompares unequal to itself; usemath.isnan.rounduses 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.sleeppauses;time.perf_countermeasures intervals — separate from datetime clocks.- Do not confuse
time.time()epoch seconds withdatetimeobjects 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/%Zneed 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+) andmath.gcdfor 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
randomis for simulations and games — not passwords or tokens.secrets.token_hex,secrets.randbeloware for security-sensitive values.- Lesson programs still use
random.seedfor demos of games and sampling. - Never seed with
datetime.now()— that reintroduces non-determinism.
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.
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)) Problem Solving Tricks
- Construct
date/datetimewith literals — skipnow()/today()in lesson code. - Always
random.seed(...)(orRandom(seed)) before random draws in demos. - ISO for storage:
date.isoformat(); pretty print withstrftime. timedeltahas no months — use calendar logic for month math.math.isclosefor float compares;Decimalfor money.math.isqrtfor integer square roots.- Use
random.sampleto pick without replacement;choicefor one item. Random(seed)isolates streams when modules share global random.- Never seed with the clock if you want reproducibility.
secretsfor tokens;randomfor games and simulations.
Practice Programs List
- Create a study plan of 5 dates starting 2026-10-25 every 3 days.
- Parse '25-10-2026' with strptime and reprint with strftime.
- Seed 42 and simulate 100 coin flips; count heads/tails.
- Write add_months using calendar.monthrange.
- Compare sum vs math.fsum on many 0.1 values.
- Build aware UTC datetime and convert to Asia/Kolkata.
- Use math.comb to compute lottery odds for small n/k.
- Implement a seeded shuffle of a deck of 8 cards.
- Compute business-day difference between two fixed dates.
- Show why 0.1 + 0.2 != 0.3 and fix with Decimal.
- Rewrite a script that used now() to use a fixed datetime.
- Create two Random instances with different seeds and print sequences.