indusai.co

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

python
from datetime import date, datetime

print(date.today())
print(datetime.now())

Creating specific dates

python
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.

python
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"))
CodeMeaningExample
%dDay15
%mMonth number09
%BMonth nameSeptember
%YYear2026
%AWeekday nameTuesday
%HHour, 24h14
%IHour, 12h02
%MMinute05
%pAM or PMPM

Parsing text into dates

strptime (string parse time) takes the text and the format it is in.

python
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

python
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

python
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

python
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

python
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

  1. Print how many days are left until the next 1 January.
  2. Generate 10 random marks between 35 and 100 with a fixed seed and print their mean and standard deviation.
  3. Parse "03 March 2026" into a date and print its weekday name.