Python datetime Module: Dates, timedelta and strftime
Make a Date in Python: datetime.date()
The datetime module works with dates and times. Its date type holds one day of the calendar: a year, a month and a day. You make one with date(year, month, day).
from datetime import date
birthday = date(2025, 3, 14)
print(birthday)
print(birthday.year)
print(birthday.month)
print(birthday.day)2025-03-14 2025 3 14
Python prints a date as year-month-day, like 2025-03-14. Each part is also there as a whole number: .year, .month and .day.
Think of it like a page torn off a wall calendar. It shows one day, and you can read its year, month and day off the page.
The rules
from datetime import datebrings in thedatetype. (The module and one of its types are both calleddatetime; you'll meet the type in the last lesson of this topic.)- The order is always year, month, day:
date(2025, 3, 14). - Write numbers with no zero in front:
3, not03. .weekday()gives the day of the week as a number: Monday is0, Sunday is6.
from datetime import date
day = date(2025, 3, 14)
print(day.weekday())4
4 means Friday: Monday 0, Tuesday 1, Wednesday 2, Thursday 3, Friday 4.
Today's date
date.today() gives the date on your computer's calendar right now:
from datetime import date
print(date.today()) # Output: today's date, like 2025-03-14
Its output changes every day, so this course's examples and tests always use fixed dates like date(2025, 3, 14).
Avoid: a day the calendar doesn't have
from datetime import date
print(date(2025, 2, 30))ValueError: day 30 must be in range 1..28 for month 2 in year 2025
Don't be scared of this one! The error even says what's allowed: February 2025 has only 28 days. Python knows every month's length and every leap year, so you don't have to.
Common beginner doubt: "Can I write the date as text, like "2025-03-14"?" Text is only text: Python can't count days with it. Make a date, and Python can. You'll turn text into a date later in this topic.
date(year, month, day) makes a date; read its parts with .year, .month and .day.