🎓 A1Learner
🔍

Python Dates & Times

A date object holds a calendar date. The parts of a date object are its year, month, and day.

Make a date and read its parts

The parts are stored as numbers. You read them with dot names.

from datetime import date

party = date(2026, 10, 22)
print(party.year)
print(party.month)
print(party.day)

A date with a time

A datetime object holds a date and a time. You can read the hour and minute too.

from datetime import datetime

moment = datetime(2026, 10, 22, 9, 30)
print(moment.hour)
print(moment.minute)

Format a date as text

strftime() uses codes like %Y for the year. %A gives the full weekday name.

from datetime import date

d = date(2026, 10, 22)
print(d.strftime("%Y-%m-%d"))
print(d.strftime("%A"))

Count the days between dates

Subtracting two dates gives a timedelta. Its .days part is the count you want.

from datetime import date

start = date(2026, 3, 10)
end = date(2026, 3, 24)
gap = end - start
print(gap.days)

Example

from datetime import date

start = date(2026, 3, 10)
end = date(2026, 3, 24)
gap = end - start
print(f"Start: {start.strftime('%A %d/%m/%Y')}")
print(f"Days between: {gap.days}")

Key points

  • Use from datetime import date to work with calendar dates
  • Use date(year, month, day) to make a fixed date
  • A date object stores one calendar date as year, month, and day parts.
  • Use .year, .month, and .day to read the parts of a date
  • Use strftime() to turn a date into formatted text
  • Subtracting two dates gives a timedelta, a length of time

In this example, both dates are fixed in March 2026. Subtracting start from end gives a timedelta. The .days part of that gap is 14. The program formats the start date with strftime(). The %A code gives the weekday name, Tuesday.

Note

date.today() gives a new value every day.

The examples here use fixed dates, so their outputs never change.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What do you get when you subtract one date from another?