← Python from Scratch Lesson 53 of 78 · 10 XP

Dates and times: datetime

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

The datetime module works with dates and times:

from datetime import date, datetime, timedelta

d = date(2024, 3, 8)
d.year, d.month, d.day          # (2024, 3, 8)
d.weekday()                     # 4 — Friday (Monday = 0)

d + timedelta(days=30)          # date(2024, 4, 7)
(date(2024, 12, 31) - d).days   # 298 — the difference in days

date.today()                    # today's date
datetime.now()                  # the date and time right now

Turning a date into a string and back:

d.strftime("%d.%m.%Y")                      # '08.03.2024'
datetime.strptime("2024-03-08", "%Y-%m-%d") # from a string to a date
date.fromisoformat("2024-03-08")            # shorter, for the YYYY-MM-DD format

Format codes: %Y is the year, %m the month, %d the day, %H:%M hours and minutes.

Task. Write a function days_between(a, b) that takes two dates as strings in the YYYY-MM-DD format and returns the number of days between them (never negative).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.