4. Datetime

The datetime module works with dates and times. Import the classes you need:

  • date(year, month, day) creates a date.
  • datetime(year, month, day, hour=0, minute=0, second=0) creates a date with a time. The time parameters are optional and default to 0.
  • Read the parts with attributes: .year, .month, .day, .hour, .minute, .second.
  • strftime(format) turns a date into text. Useful codes: %Y year with century, %m month 01–12, %d day 01–31, %H, %M, %S for time.
  • timedelta(days=..., hours=..., minutes=...) is a duration. Add it to a date to move forward; subtract it to move backward.
  • date.today() and datetime.now() read the current date and time. They are useful in real programs, but not in these exercises: the result changes on every run, so we build fixed dates instead.

Coming from JavaScript? Python months are 1-based: date(2026, 10, 27) is October 27. In JS, new Date(2026, 9, 27) is also October because JS months are 0-based.

#01

Create a date

Import date from datetime and print the date 27 October 2026 by creating date(2026, 10, 27).

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Read the parts of a date

Create the date date(2026, 10, 27) and print its year, month and day, each on its own line.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Format a date with strftime

Create the date date(2026, 10, 27) and print it with strftime("%d-%m-%Y").

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Add a time

Import datetime from datetime and print the datetime for 27 October 2026 at 14:30 by creating datetime(2026, 10, 27, 14, 30).

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

Add days with timedelta

Create the date date(2026, 10, 27), add timedelta(days=10) and print the result.

Print exactly:

Create a free account to save your progress and unlock chapter 2.