🧰 Standard Library Tour, lesson 2 of 6
Dates and times
Do calendar math with date, datetime and timedelta.
10 min
1 exercise
1 quiz
0/2 solved
Getting Python ready… examples can run in a moment.
The datetime module does calendar math for you, so
you never have to remember how many days February has.
date(2024, 3, 15): a calendar daydatetime(2024, 3, 15, 14, 30): a day and a timetimedelta(days=7): a duration to add or subtract
from datetime import date, datetime, timedelta
Dates and durations
2024 is a leap year, so three days after Feb 27 is March 1. Change the year to 2023 and compare.
What does this print?
Text ↔ dates. strftime (format) turns a date
into text; datetime.strptime (parse) turns text
into a datetime. Common codes:
%Yyear,%mmonth (01–12),%dday%H:%M24-hour time%Aweekday name,%Bmonth name
For the standard YYYY-MM-DD format, use
date.fromisoformat() and .isoformat().
Format and parse
Two minutes after 23:59 on Dec 31 is a new year.
Try timedelta(hours=36) instead.
How old? Which weekday?
Tuples compare item by item (month first, then day), a
neat trick. weekday() counts Monday as 0 and Sunday
as 6.
Library due dates
Write two functions:
due_date(borrowed, days=14)returns the date the book is duelate_fee(due, returned)returns 0.25 for each day late, and 0 if returned on time or early