The standard library
Python comes with a large set of modules ready to import, nothing to install. People call this "batteries included". This topic covers the ones you will use most in real projects.
datetime: parse, format and calculate with dates
from datetime import datetime, date, timedelta
d = datetime.strptime("29-10-2026", "%d-%m-%Y") # parse: text to a date
print(d.strftime("%A, %d %B %Y")) # format: Thursday, 29 October 2026
due = date.today() + timedelta(days=15) # add days
left = (date(2027, 3, 1) - date.today()).days # difference in days
| Code | Meaning | Example |
|---|---|---|
%d | day, 2 digits | 29 |
%m | month number | 10 |
%B / %b | month name, full / short | October / Oct |
%Y | 4-digit year | 2026 |
%A | weekday name | Thursday |
%H:%M | 24-hour time | 17:05 |
%I:%M %p | 12-hour time | 05:05 PM |
Remember: strptime = string *parse* to time; strftime = string *format* from time.
pathlib: work with files and folders
from pathlib import Path
folder = Path("reports")
folder.mkdir(exist_ok=True) # create it if it does not exist
file = folder / "march.txt" # '/' joins path parts
file.write_text("Total: 500", encoding="utf-8")
print(file.exists(), file.name, file.suffix) # True march.txt .txt
for p in Path(".").glob("*.csv"): # every CSV in the current folder
print(p.name, p.stat().st_size, "bytes")
shutil: copy, move and back up
import shutil
shutil.copy("marks.csv", "backup/marks.csv") # copy a file
shutil.move("old.txt", "archive/old.txt") # move or rename
shutil.make_archive("backup", "zip", "reports") # zip a whole folder
A downloads organiser combines both: loop over files with Path.glob, look at each suffix, and shutil.move the file into a folder for its type.
collections: smarter containers
Counter: count anything
from collections import Counter
votes = ["Asha", "Ravi", "Asha", "Meena", "Asha"]
c = Counter(votes)
print(c["Asha"]) # 3
print(c.most_common(2)) # [('Asha', 3), ('Ravi', 1)]
defaultdict: no KeyError for new keys
from collections import defaultdict
by_class = defaultdict(list)
for name, cls in [("Asha", 10), ("Ravi", 9), ("Meena", 10)]:
by_class[cls].append(name) # a missing key starts as an empty list
print(dict(by_class)) # {10: ['Asha', 'Meena'], 9: ['Ravi']}
namedtuple and deque
from collections import namedtuple, deque
Point = namedtuple("Point", "lat lon")
ranchi = Point(23.34, 85.31)
print(ranchi.lat) # read fields by name
queue = deque(["A", "B"])
queue.append("C") # join at the back
print(queue.popleft()) # A -- fast removal from the front
Regular expressions: find patterns in text
A regular expression (regex) describes a pattern of text, such as "10 digits" or "an email address".
| Pattern | Matches |
|---|---|
\d | one digit |
\w | a letter, digit or underscore |
\s | a space, tab or new line |
. | any character |
[A-Z] | one capital letter |
+ | one or more of the previous |
* | zero or more |
{3} / {2,4} | exactly 3 / between 2 and 4 |
^ and $ | start and end of the text |
Using re: search, findall, fullmatch, sub
import re
text = "Call 9876543210 or 9123456780"
print(re.findall(r"\d{10}", text)) # both numbers, as a list
m = re.search(r"\d{10}", text) # the first match, or None
if m:
print(m.group())
pan = "ABCDE1234F"
print(bool(re.fullmatch(r"[A-Z]{5}\d{4}[A-Z]", pan))) # True: the whole text must match
print(re.sub(r"\s+", " ", "too many spaces")) # 'too many spaces'
Always write patterns as raw strings (r"..."), so backslashes reach re unchanged.
| Function | Use it to |
|---|---|
re.search | find the first match anywhere |
re.findall | get every match as a list |
re.fullmatch | check that the whole text fits the pattern (validation) |
re.sub | replace every match |
Common mistakes
- Mixing up
strptimeandstrftime. - Using
re.searchto validate input: it accepts extra text around the match. Usere.fullmatch. - Forgetting the
rbefore a regex string. - Joining paths with
+and backslashes by hand instead ofPath(...) / "name".
Key points
datetimeparses withstrptime, formats withstrftime, and adds days withtimedelta.pathlib.Pathandshutilhandle files and folders.Countercounts;defaultdictgives new keys a starting value.re.findall,re.fullmatchandre.subfind, validate and replace text patterns.
Practice questions
1. Convert "2026-12-25" into "25 Dec 2026".
from datetime import datetime
d = datetime.strptime("2026-12-25", "%Y-%m-%d")
print(d.strftime("%d %b %Y"))2. Find the three most common words in a sentence.
from collections import Counter
print(Counter(sentence.lower().split()).most_common(3))3. Write a regex that checks for a 6-digit Indian PIN code.
re.fullmatch(r"\d{6}", pin) (or r"[1-9]\d{5}", since PIN codes do not start with 0).
4. List the names of all .jpg files in a folder.
from pathlib import Path
print([p.name for p in Path("photos").glob("*.jpg")])5. What is the difference between re.search and re.fullmatch?
search finds the pattern anywhere in the text; fullmatch succeeds only if the entire text matches.