Codiqo

Learn Python · lesson 41 of 60 · about 8 minutes

Importing Modules

Count the days to the school holidays: use Python's built-in modules, like math, random and datetime, instead of writing everything yourself.

What you'll learn

  • Import a module
  • Import specific names with from
  • Explore math, random and datetime

Days to the holidays

Sam wants the assistant to count down to the school holidays, which start on 18 December. Working out days between dates by hand means knowing how long every month is, and leap years too. Python already knows: from datetime import date brings in the date type, date.fromisoformat("2026-12-01") turns the text Sam types into a date, and taking one date from another gives the gap, whose .days is the answer. Text that isn't a date makes fromisoformat raise a ValueError, which the assistant catches like any other.

Batteries included

Python ships with a huge standard library of modules: ready-made code you can load with import.

  • import math gives you math.sqrt, math.pi and more
  • from math import sqrt lets you write sqrt without the prefix
  • import random as r gives a module a shorter nickname

math in action

import math
from math import sqrt

print(math.floor(3.7), math.ceil(3.2))
print(sqrt(81))
print(round(math.pi, 2))

Output

3 4
9.0
3.14

random and datetime

import random
from datetime import date

roll = random.randint(1, 6)
print(1 <= roll <= 6)
print(random.choice(["only"]))

launch = date(2026, 1, 15)
print(launch.year, launch.strftime("%d/%m"))

Output

True
only
2026 15/01

Dates from text

date.fromisoformat reads a date written year first, like 2026-12-01. Subtracting two dates gives a time difference, and its .days is a whole number of days, negative if the second date comes later. A date that can't exist, like 30 February, raises a ValueError just like text that isn't a date at all.

Counting days

from datetime import date

start = date.fromisoformat("2026-12-01")
end = date(2026, 12, 18)
print((end - start).days)
try:
    date.fromisoformat("2026-02-30")
except ValueError:
    print("30 February isn't a date")

Output

17
30 February isn't a date

Tip

Put imports at the very top of a file. Anyone reading it can see at a glance what the program depends on.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.