Dates, times and math
Four standard library modules come up in nearly every script: datetime for dates and times, math for numeric functions, random for randomness and statistics for simple descriptive stats.
Today's date and the current time
from datetime import date, datetime
print(date.today())
print(datetime.now())Creating specific dates
from datetime import date, datetime
d = date(2026, 1, 26)
print(d, d.year, d.month, d.day)
print(d.weekday()) # Monday is 0
print(d.strftime("%A"))
dt = datetime(2026, 1, 26, 9, 30)
print(dt)Formatting dates as text
strftime (string format time) uses codes for each part.
from datetime import datetime
now = datetime(2026, 9, 15, 14, 5)
print(now.strftime("%d/%m/%Y"))
print(now.strftime("%d %B %Y, %I:%M %p"))
print(now.strftime("%Y-%m-%d %H:%M:%S"))| Code | Meaning | Example |
|---|---|---|
%d | Day | 15 |
%m | Month number | 09 |
%B | Month name | September |
%Y | Year | 2026 |
%A | Weekday name | Tuesday |
%H | Hour, 24h | 14 |
%I | Hour, 12h | 02 |
%M | Minute | 05 |
%p | AM or PM | PM |
Parsing text into dates
strptime (string parse time) takes the text and the format it is in.
from datetime import datetime
d = datetime.strptime("15-09-2026", "%d-%m-%Y")
print(d.date())Dates in ISO format (2026-09-15) can use date.fromisoformat() directly.
Date arithmetic with timedelta
from datetime import date, timedelta
start = date(2026, 9, 15)
print(start + timedelta(days=30))
print(start - timedelta(weeks=2))
exam = date(2026, 12, 1)
print((exam - start).days, "days until the exam")The math module
import math
print(math.sqrt(2))
print(math.pow(2, 8), 2 ** 8)
print(math.floor(2.7), math.ceil(2.1), math.trunc(-2.7))
print(math.gcd(24, 36))
print(math.log(1000, 10), math.log2(8), math.exp(1))
print(math.sin(math.radians(90)))
print(math.inf, -math.inf, math.nan)
print(math.isclose(0.1 + 0.2, 0.3))The random module
import random
random.seed(42) # same results every run
print(random.randint(1, 100))
print(random.random())
print(random.uniform(1.5, 2.5))
print(random.choice(["rock", "paper", "scissors"]))
print(random.sample(range(1, 50), 6))
deck = list(range(10))
random.shuffle(deck)
print(deck)Setting a seed makes experiments reproducible, which matters a lot in machine learning.
The statistics module
import statistics as st
marks = [72, 85, 61, 94, 85, 78]
print(st.mean(marks))
print(st.median(marks))
print(st.mode(marks))
print(round(st.stdev(marks), 2))Practice
- Print how many days are left until the next 1 January.
- Generate 10 random marks between 35 and 100 with a fixed seed and print their mean and standard deviation.
- Parse
"03 March 2026"into a date and print its weekday name.
