livepython.net
CHAPTER 18Python Modules
18.4  DATETIME

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).

PYTHONedit me
from datetime import date

birthday = date(2025, 3, 14)
print(birthday)
print(birthday.year)
print(birthday.month)
print(birthday.day)
OUTPUT
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 date brings in the date type. (The module and one of its types are both called datetime; 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, not 03.
  • .weekday() gives the day of the week as a number: Monday is 0, Sunday is 6.
PYTHONedit me
from datetime import date

day = date(2025, 3, 14)
print(day.weekday())
OUTPUT
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

PYTHONedit me
from datetime import date

print(date(2025, 2, 30))
OUTPUT
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.

your turnPredict the output

What will this print?

from datetime import date d = date(2025, 1, 5) print(d)
Your turn! What will this code show on the screen?
your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Days Between Two Dates: timedelta in Python

Subtract one date from another, and you get a timedelta: an amount of time, like "286 days". Its .days gives the number of days as an int.

PYTHONedit me
from datetime import date

today = date(2025, 3, 14)
new_year = date(2026, 1, 1)
wait = new_year - today
print(wait)
print(wait.days, "days to go")
OUTPUT
293 days, 0:00:00
293 days to go

The 0:00:00 part is hours, minutes and seconds: a timedelta can hold those too. For whole days, use .days.

Think of it like the countdown on a calendar app. You don't care what the date is in the middle; you want "how many days until?".

Add days to a date

Go the other way: a date plus a timedelta gives a new date. Make one with timedelta(days=…):

PYTHONedit me
from datetime import date, timedelta

borrowed = date(2025, 3, 14)
due = borrowed + timedelta(days=21)
print("Due back:", due)
OUTPUT
Due back: 2025-04-04

Python crossed from March into April by itself. It knows every month's length and every leap year.

The rules

CalculationGives
date - datea timedelta (use .days)
date + timedeltaa new date, later
date - timedeltaa new date, earlier
date + dateTypeError
  • timedelta(days=7) and timedelta(weeks=1) are the same amount of time.
  • An earlier date minus a later one gives a negative number of days. Use abs() when only the size matters.

Avoid: adding two dates

PYTHONedit me
from datetime import date

print(date(2025, 3, 14) + date(2025, 3, 1))
OUTPUT
TypeError: unsupported operand type(s) for +: 'datetime.date' and 'datetime.date'

What would "the 14th of March plus the 1st of March" even mean? Nothing! You can add an amount of time to a date, but not another date.

Common beginner doubt: "Is the first day counted?" No. From the 14th to the 15th is 1 day. Add 1 yourself if you need to count both the first and the last day, like the days of a holiday.

date - date gives a timedelta (use .days); date + timedelta(days=n) gives a new date.

your turnType the output

Type what this prints

from datetime import date gap = date(2025, 5, 10) - date(2025, 5, 3) print(gap.days)
Read the code line by line, then type the output exactly.
your turnFix the code

Fix the code so it prints the date 10 days after the 25th of December 2025: 2026-01-04

It should print: 2026-01-04

from datetime import date

start = date(2025, 12, 25)
print(start + 10)
This code does not work yet. Fix it, then press Run.

Format a Date in Python with strftime()

strftime() turns a date into text in any layout you want. You give it a pattern, and each format code (a % and a letter) is replaced by one part of the date.

PYTHONedit me
from datetime import date

day = date(2025, 3, 14)
print(day.strftime("%d/%m/%Y"))
print(day.strftime("%A, %d %B %Y"))
print(day.strftime("%b %d"))
OUTPUT
14/03/2025
Friday, 14 March 2025
Mar 14

The name means "string from time". Everything in the pattern that isn't a format code, like /, , and spaces, is kept as it is.

Think of it like a form with blanks: "Today is ___, the ___ of ___". strftime() fills each blank with the right part of the date.

The format codes you'll use most

CodeMeansFor 14 March 2025
%dday, two digits14
%mmonth, two digits03
%Yyear, four digits2025
%yyear, two digits25
%Bmonth nameMarch
%bshort month nameMar
%Aweekday nameFriday
%ashort weekday nameFri
  • Capital letters matter: %Y is 2025, but %y is 25. %m is the month, but %M is minutes!
  • strftime() gives back a string: you can join it, print it, or put it in an f-string.

The same date, many countries

PYTHONedit me
from datetime import date

day = date(2025, 7, 4)
print("India:", day.strftime("%d-%m-%Y"))
print("USA:", day.strftime("%m/%d/%Y"))
print("Japan:", day.strftime("%Y/%m/%d"))
OUTPUT
India: 04-07-2025
USA: 07/04/2025
Japan: 2025/07/04

That's why the month name is often safest: "4 July 2025" can't be misread.

Common mistake: %M for the month

PYTHONedit me
from datetime import date

print(date(2025, 3, 14).strftime("%d/%M/%Y"))
OUTPUT
14/00/2025

No error, only a wrong answer: %M is the minutes, and a date has no time, so it's 00. Use a small %m for the month.

Common beginner doubt: "Do I have to remember all these codes?" No. Keep a table like the one above nearby, or search "python strftime codes". Even experienced programmers look them up.

strftime() turns a date into text: each format code, like %d or %B, becomes one part of the date.

your turnFill the gap

Print the date as 14 March 2025

from datetime import date day = date(2025, 3, 14) print(day.strftime("%d ? %Y"))

It should print: 14 March 2025

Which piece makes this code work?
your turnPick the right idea

What type of value does day.strftime("%Y") give back?

Think about it, then pick one.

Read a Date from Text, and Add a Time with datetime

date.fromisoformat() turns text like "2025-03-14" into a real date. And the datetime type holds a date and a time together.

PYTHONedit me
from datetime import date

text = input()
day = date.fromisoformat(text)
print(day.strftime("%A, %d %B %Y"))
OUTPUT
Friday, 14 March 2025

"ISO format" is the year-month-day layout, 2025-03-14, the same one Python prints. It's the world standard for writing dates, so it's the easiest one for a program to read.

Think of it like a translator. The user types text, and fromisoformat() translates it into a date Python can count with.

The rules

  • date.fromisoformat("2025-03-14") needs exactly YYYY-MM-DD: four digits, two digits, two digits.
  • "2025-3-14" or "14/03/2025" raise a ValueError.
  • Catch that error with try/except from chapter 17, and a typo can't crash your program:
PYTHONedit me
from datetime import date

text = input()
try:
    day = date.fromisoformat(text)
    print("Year:", day.year)
except ValueError:
    print("Please type the date as YYYY-MM-DD")
OUTPUT
Please type the date as YYYY-MM-DD

Dates with a time: datetime

A datetime has everything a date has, plus .hour, .minute and .second. Make one with the time after the date:

PYTHONedit me
from datetime import datetime, timedelta

start = datetime(2025, 3, 14, 9, 30)
print(start)
print(start.hour, start.minute)
end = start + timedelta(hours=2, minutes=45)
print(end.strftime("%H:%M"))
OUTPUT
2025-03-14 09:30:00
9 30
12:15

%H is the hour (00 to 23) and %M the minutes. datetime.now() gives the date and time right now; like date.today(), its output changes every run, so it stays out of the tested examples:

from datetime import datetime

print(datetime.now())   # Output: like 2025-03-14 09:30:12.345678

Common beginner doubt: "import datetime or from datetime import datetime?" Both work, but they're different names. After import datetime, write datetime.date(...) and datetime.datetime(...). After from datetime import date, datetime, write date(...) and datetime(...). Pick one style per program.

date.fromisoformat() reads a YYYY-MM-DD date from text; datetime adds hours and minutes.

your turnPredict the output

Remember try and except from chapter 17?

try: number = int("12a") print("Number:", number) except ValueError: print("Not a number")
Your turn! What will this code show on the screen?
your turnPick the right idea

Which text can date.fromisoformat() read?

Think about it, then pick one.

Practice: datetime

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 167.Python Program to Find the Number of Days Between Two DatesEasySolve
  2. 168.Python Program to Calculate Age from a Date of BirthMediumSolve
  3. 169.Python Program to Make a Library Due Date and Fine CalculatorHardSolve