Module 11 · Lesson 02
Dates and Times
Work with calendars and clocks: create dates and datetimes, do arithmetic with timedelta, compare them, and turn them into text and back with strftime, strptime and ISO format.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Make and read dates
- Add time with timedelta
- Dates to text and back
- Watch a book go overdue
Calendars in code
`datetime` knows how long each month is, when leap years fall and what day of the week a date is.
date
date(2026, 7, 4)is one day..year,.monthand.dayread its parts.timedelta
timedelta(days=10)is a length of time you can add or subtract.Compare
Dates compare with
<and>, and subtracting two dates gives the gap between them.Text
strftimeturns a date into text.strptimeandfromisoformatread text back.
Dates everywhere
Almost every app needs to know when something happened or is due.
- BirthdaysCount the days until your next birthday.
- Daily rewardsCheck whether a whole day has passed since the last login.
- BookingsA hotel adds the number of nights to the check-in date.
- CalendarsFind which weekday the 1st of each month falls on.
Working out a due date
This line finds the date two weeks after another. Tap each part to see its job.
Part 1 of 5
result:A new date. start itself does not change.
Move through the calendar
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Make a date
A date has a year, a month and a day. Python checks that it really exists.
Your turn: Make the date of your birthday and print its weekday.
from datetime import date
launch = date(2026, 7, 4)
print(launch)
print(launch.year, launch.month, launch.day)
print(launch.strftime("%A"))Press Run to see what it prints.Watch a library book go overdue
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- from datetime import date, timedelta
- borrowed = date(2026, 3, 25)
- due = borrowed + timedelta(days=14)
- returned = date(2026, 4, 10)
- late = (returned - due).days
- print("Due", due)
- print("Days late:", late)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.The day after New Year's Eve:
from datetime import date, timedelta
print(date(2026, 12, 31) + timedelta(days=1))0 of 6 answered
Common date misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
from datetime import date, datetime, timedelta
date(2024, 3, 15) # a calendar day
datetime(2024, 3, 15, 14, 30) # day and time
d + timedelta(days=7) # move a date
(d2 - d1).days # days between
d.weekday() # Monday 0 ... Sunday 6
d.strftime("%d %B %Y") # date -> text
datetime.strptime("15/03/2024", "%d/%m/%Y") # text -> datetime
d.isoformat() / date.fromisoformat("2024-03-15")Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
Library due dates
Books are lent for 21 days. For each loan, work out the due date, and report how many days overdue it is on a given day, or how many days are left.
from datetime import date, timedelta
LOAN = timedelta(days=21)
today = date(2024, 3, 1)
loans = [("Emma", date(2024, 2, 1)), ("Dune", date(2024, 2, 15)), ("Ulysses", date(2024, 2, 9))]
for title, borrowed in sorted(loans, key=lambda loan: loan[1]):
due = borrowed + LOAN
days = (due - today).days
if days < 0:
status = f"{-days} days overdue"
else:
status = f"{days} days left"
print(f"{title}: due {due.strftime('%d %b')}, {status}")Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Doing date maths with numbers
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
day, month = 30, 1 day = day + 5 print(day, month)
Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- E-commerce
Planning a delivery date
An online shop promises delivery in three working days. Orders placed after 2 pm count from the next day, and weekends are skipped.
Why Python fits
strptimereads each order time, the hour decides the start day, andweekday() < 5counts only Monday to Friday. All the calendar knowledge comes from the datetime module, so month ends and leap years need no special code.Pythonfrom datetime import datetime, timedelta def delivery_date(ordered, working_days=3): day = ordered.date() if ordered.hour >= 14: day += timedelta(days=1) added = 0 while added < working_days: day += timedelta(days=1) if day.weekday() < 5: added += 1 return day orders = ["2024-03-13 10:15", "2024-03-14 16:40", "2024-03-15 09:00"] for text in orders: ordered = datetime.strptime(text, "%Y-%m-%d %H:%M") print(ordered.strftime("%a %H:%M"), "->", delivery_date(ordered).strftime("%A %d %B"))OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
How do I add a month?
Why does my weekday name come out in English?
How do I measure how long something took?
Can I compare a datetime with a date?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 9 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.