Legends ofPythos
Claim your name
Writing Real Programs

Dates and times

Lesson 12 of 16

Watch the lesson1:12 · with Sigrid
Python has a built-in datetime module that handles dates, times, and durations. It is part of the standard library, so you never need to install anything extra.

Creating a date

from datetime import date

today = date.today()
print(today)
Creates and prints today's date.
date objects hold a year, month, and day. You can create one for any specific day by passing three integers: year, month, then day. Months are 1-indexed (January is 1). Days run from 1 to the last valid day of that month.
from datetime import date

birthday = date(2003, 5, 14)
print(birthday.year)   # 2003
print(birthday.month)  # 5
print(birthday.day)    # 14

Measuring the gap between two dates

from datetime import date

day_one = date(2024, 1, 1)
day_two = date(2024, 3, 15)

gap = day_two - day_one
print(gap.days)   # 74
Subtracting two date objects gives you a timedelta. A timedelta represents a duration of time. You can inspect its .days, .seconds, and .microseconds attributes to see exactly how long the gap is.

Adding days with timedelta

from datetime import date, timedelta

today = date(2024, 10, 5)
next_week = today + timedelta(days=7)
print(next_week)   # 2024-10-12

Formatting with strftime

from datetime import date

d = date(2024, 12, 25)
print(d.strftime('%Y-%m-%d'))   # 2024-12-25
print(d.strftime('%B %d, %Y'))  # December 25, 2024
strftime stands for string format time. You pass it a format string made of special codes. %Y is the four-digit year, %m is the zero-padded month (01-12), and %d is the zero-padded day (01-31). Use this to turn dates into human-readable text.

Your turn

0 of 2 solved

Exercise 1

+30 XP
Write a function called days_between(start, end) that returns the number of days between two dates. Both arguments are date objects, which you create yourself in this exercise. The result should be an integer.

Create two specific dates: start = January 1st, 2024 and end = March 31st, 2024. Then call the function with those two dates and print the result.
Write your Python here.

Run your code to check it against the tests.

Exercise 2

+30 XP
Write a function called format_date(d) that takes a single date object and returns it as a string in the format 'YYYY-MM-DD' (for example, '2024-12-25').

In your code below the function definition:
  • Create a date for December 25th, 2024.
  • Add seven days to it using timedelta and store that result in one_week_later.
  • Call format_date(one_week_later) and print the returned string.
Write your Python here.

Run your code to check it against the tests.