Dates and times

Standard Library Tour, lesson 2 of 6

🧰 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 day
  • datetime(2024, 3, 15, 14, 30): a day and a time
  • timedelta(days=7): a duration to add or subtract
from datetime import date, datetime, timedelta
Example

Dates and durations

2024 is a leap year, so three days after Feb 27 is March 1. Change the year to 2023 and compare.

Quiz

What does this print?

Text ↔ dates. strftime (format) turns a date into text; datetime.strptime (parse) turns text into a datetime. Common codes:

  • %Y year, %m month (01–12), %d day
  • %H:%M 24-hour time
  • %A weekday name, %B month name

For the standard YYYY-MM-DD format, use date.fromisoformat() and .isoformat().

Example

Format and parse

Two minutes after 23:59 on Dec 31 is a new year. Try timedelta(hours=36) instead.

Example

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.

Exercise

Library due dates

Write two functions:

  • due_date(borrowed, days=14) returns the date the book is due
  • late_fee(due, returned) returns 0.25 for each day late, and 0 if returned on time or early