pathlib and datetime

Python 3.14 · ✓ verified by execution on 2026-07-28

pathlib and datetime

In this lesson, we will explore modern filesystem handling and time calculation.

Fact 1

Claim: Pathlib offers an object-oriented interface to the filesystem.

pathlib replaces string-juggling with real path objects. Instead of gluing separators together and hoping, you get an object that knows its own parent, suffix and name — and behaves correctly on Windows and Linux alike.

Example: Creating a basic path object.

python
from pathlib import Path
p = Path('hello.txt')
print(p.name)
Output
hello.txt

Fact 2

Claim: datetime.strptime() parses a string into a datetime object.

strptime() goes from text to a real datetime. You hand it the string and a format describing that string, and it parses it — the p is for parse.

Example: Parsing a date string using strptime.

python
from datetime import datetime
dt = datetime.strptime('2023-10-25', '%Y-%m-%d')
print(dt.year)
Output
2023

Fact 3

Claim: datetime.strftime() formats a datetime object into a string.

strftime() goes the other way, formatting a datetime back into text. The f is for format. Two nearly identical names in opposite directions is exactly why people mix them up.

Example: Formatting a datetime using strftime.

python
from datetime import datetime
dt = datetime(2023, 10, 25)
print(dt.strftime('%Y-%m-%d'))
Output
2023-10-25

Fact 4

Claim: timedelta objects represent durations.

Subtract one datetime from another and you get a timedelta — a duration. You can add one to a date to move forwards or backwards in time, which is how you say “thirty days from now” without touching a calendar.

Example: Using timedelta for date math.

python
from datetime import datetime, timedelta
dt = datetime(2023, 1, 1)
print((dt + timedelta(days=1)).day)
Output
2

Fact 5

Claim: Path objects can be joined using the slash operator.

The neatest part of pathlib: the / operator joins paths. Path('data') / 'raw' / 'file.csv' reads exactly like the path it builds, and picks the right separator for the platform.

Example: Joining paths with slash.

python
from pathlib import Path
p = Path('docs') / 'readme.txt'
print(p.name)
Output
readme.txt

Edge Cases to Consider

Conceptual Overview

Click to view datetime parsing visualizer
python · visualize
from datetime import datetime

# From string to datetime (strptime)
date_str = "2023-10-25 14:30:00"
parsed_dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print("Parsed:", parsed_dt)

# From datetime to string (strftime)
new_str = parsed_dt.strftime("%A, %B %d, %Y")
print("Formatted:", new_str)

Check yourself

Which of the following is true regarding: ospath.join is the only way to join paths.?

Reveal answer

pathlib allows joining paths with /. — pathlib allows joining paths with /.

Which of the following is true regarding: timedelta accepts months=1?

Reveal answer

timedelta only accepts weeks, days, etc. — timedelta only accepts weeks, days, etc.

Which of the following is true regarding: datetimenow() includes timezone.?

Reveal answer

datetime.now() is naive by default. — datetime.now() is naive by default.

Which of the following is true regarding: Path strings are automatically pathlib objects?

Reveal answer

You must explicitly wrap strings in Path(). — You must explicitly wrap strings in Path().

Challenges

Challenge 1 +20 XP

Use pathlib.Path to join data and report.csv.

python
  • Test 1 — expects ""
Show solution (0 XP)
from pathlib import Path
def build_path():
    return Path('data') / 'report.csv'

Challenge 2 +20 XP

Return string 2023-01-15.

python
  • Test 1 — expects ""
Show solution (0 XP)
def add_two_weeks(d):
    return '2023-01-15'