HomeCourseModule 06 › Working with dates

Working with dates

Module 06 · Data Structures8 min readBeginner

What you'll learn

  • Create date and datetime objects
  • Parse a date string with strptime
  • Do date arithmetic with timedelta

The two types you'll use

from datetime import date, datetime, timedelta

d = date(2026, 5, 16)           # just a date
dt = datetime(2026, 5, 16, 14, 30, 0)   # date + time

Today / now

date.today()                # date(2026, 5, 16)
datetime.now()              # full timestamp

Parsing a string

datetime.strptime("2026-05-16", "%Y-%m-%d")
datetime.strptime("16/05/2026", "%d/%m/%Y")
datetime.strptime("May 16, 2026", "%B %d, %Y")

The format codes are documented at strftime.org. The big ones: %Y year, %m month, %d day, %H hour, %M minute.

Formatting back to a string

d = date.today()
d.isoformat()                   # '2026-05-16'
d.strftime("%B %d, %Y")         # 'May 16, 2026'
d.strftime("%A")                # 'Saturday'

Date arithmetic

today = date.today()
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(weeks=1)

age_days = (today - date(1990, 1, 1)).days   # how many days old

Walkthrough: end-of-month dates for the next year

Build a list of month-ends

from datetime import date
from calendar import monthrange

year = 2026
month_ends = []
for m in range(1, 13):
    last_day = monthrange(year, m)[1]
    month_ends.append(date(year, m, last_day))

for d in month_ends:
    print(d.isoformat())

Key takeaways

  • date = just a date. datetime = date + time.
  • strptime parses; strftime formats.
  • Subtract two dates → timedelta; .days gives you the day count.
  • Pandas has even better date tools — covered in Module 9.

Days until your birthday

Write a script that prints how many days until your next birthday.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.