Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

2.7 (3 of 3): Working with dates and times

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

40 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

The receipt with the wrong date

A shop receipt says 05/12/2026. Is that 5 December or 12 May? In the UK it is 5 December. In the USA it is 12 May.

Programs need to read dates and show dates. Python has pre-written code for this. This lesson shows three commands.

Key words

WordWhat it meansExample
datetimeA Python library (a set of ready-made code) for dates and times.from datetime import datetime
now()Gives the date and time right now.datetime.now()
Format codeA short code for one part of a date.%Y is the year
strftime()Turns a date into text. The name means "string from time".when.strftime("%d/%m/%Y")
strptime()Turns text into a date. The name means "string parse time".datetime.strptime("25/12/2026", "%d/%m/%Y")
StringText inside quote marks."25/12/2026"
FunctionA named piece of code that does one job.len()
ValidationChecking that data makes sense before you use it.Is this a real date?

The cells students fill in are left blank in this preview.

Try it: the date right now

Code: python
from datetime import datetime

now = datetime.now()
print(now)
print(now.strftime("%d/%m/%Y"))
print(now.strftime("%H:%M"))

# Run it twice. The answer changes, because the time moves on.

Make a free account to save your work and track your progress.

A date is not the same as text

Inside Python, a date is a special kind of value. It is not the same as the letters and digits you see on a screen.

To show a date to a person, you make text from it. To use text that a person typed, you make a date from it.

Two commands do these jobs. They go in opposite directions.

Date to text, and text to date

A box saying A date value above a box saying Text: 25/12/2026, an arrow marked strftime going down from the date to the text and an arrow marked strptime going back up from the text to the date.A box saying A date value above a box saying Text: 25/12/2026, an arrow marked strftime going down from the date to the text and an arrow marked strptime going back up from the text to the date.

Worked example: the format codes

CodeStands forExample for 25 December 2026, 9:30 am
%dDay of the month, two digits25
%mMonth as a number, two digits12
%YYear, four digits2026
%BMonth name in fullDecember
%ADay of the week in fullFriday
%HHour on a 24 hour clock09
%MMinutes30

The cells students fill in are left blank in this preview.

Try it: date to text

Code: python
from datetime import datetime

when = datetime(2026, 12, 25, 9, 30)

print(when.strftime("%d/%m/%Y"))
print(when.strftime("%A %d %B %Y"))
print(when.strftime("%H:%M"))

# Change the format text. Try "%Y-%m-%d".
# Anything that is not a code, such as the / sign, is copied as it is.

Make a free account to save your work and track your progress.

Quick check: format codes

Have a go

Quick check: format codes

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Text to date: strptime

strptime() reads text and makes a date. You must tell it how the text is laid out, with the same format codes.

If the text does not match, Python stops with an error called ValueError. That is useful. It is a free validation check: a real date passes, and "31/02/2026" or "tomorrow" fails.

Try it: text to date, with a check

Code: python
from datetime import datetime

text = "25/12/2026"

try:
    when = datetime.strptime(text, "%d/%m/%Y")
    print("A real date. The month is", when.strftime("%B"))
except ValueError:
    print("That is not a date like 25/12/2026.")

# Try "31/02/2026", "25-12-2026" and "tomorrow".

Make a free account to save your work and track your progress.

Watch: a date both ways

Press Play on the short film below. It reads the receipt's date with the format codes you have just used. Watch which code gives the minutes, and what strptime() does with a date that is not real.

Film: working with dates and times

Working with dates and times

Every scene, as text

  1. A receipt's date as text: text = "05/12/2026". In the UK it is 5 December; in the USA it is 12 May. As text it is only digits and / signs, so a program cannot tell which.
  2. The datetime library is ready-made code for dates and times. datetime.now() gives the date and time right now, so what it prints changes every run. This example ran at 9:30 am on 25 December 2026: it prints 25/12/2026 and 09:30.
  3. when is set to a date value, not text. strftime(), string from time, makes text from it with format codes: %d the day, %m the month, %Y the year, and each / copied as it is, so it prints 25/12/2026. %A gives the day of the week and %B the month name: Friday 25 December 2026.
  4. Myth (false): %m is the minutes. strftime("%H:%m") prints 09:12, because %m is the month, 12. The cure: %M is the minutes, and strftime("%H:%M") prints 09:30.
  5. strptime() goes the other way: it reads text and makes a date from it. You give it the layout with the same codes. %d comes first, so the day comes first: the receipt is 5 December, and it prints 05 December 2026.
  6. strptime() also checks. "31/02/2026" has the right shape, but February has no 31st day, so strptime() stops with a ValueError. except ValueError: runs, and it prints Not a real date: a free validation check.

Match the code to its job

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Try it: what day is it?

Code: python
from datetime import datetime

when = datetime.strptime("25/12/2026", "%d/%m/%Y")

print(when.strftime("%A"))

# strptime made a date from the text. strftime made the day name.
# Change the text to 26/12/2026 and guess the answer first.

Make a free account to save your work and track your progress.

Extra: Try it: days between two dates

Code: python
from datetime import datetime

start = datetime.strptime("01/12/2026", "%d/%m/%Y")
end = datetime.strptime("25/12/2026", "%d/%m/%Y")

print(end.year, end.month, end.day)

gap = end - start
print(gap.days)

# A date knows its year, month and day.
# One date minus another gives the gap. 25 minus 1 is 24 days.
# Change the end date to 31/12/2026 and work out the answer first.

Make a free account to save your work and track your progress.

Your turn: four date functions

Finish four functions.

  1. show_date gives back text like 25/12/2026 from a date.
  2. read_date makes a date from that kind of text, or gives back None when the text is not a real date. Use try and except.
  3. day_name gives back the day of the week, such as Friday.
  4. is_weekend gives back True if a date text is a Saturday or a Sunday, and False if not.

Press Run Tests to check your work.

Code: python
from datetime import datetime


def show_date(when):
    # when is a datetime. Give back text like 25/12/2026 (day, month, year).
    return None


def read_date(text):
    # text should look like 25/12/2026. Give back a datetime.
    # If the text is not a real date, give back None.
    return 0


def day_name(text):
    # text looks like 25/12/2026. Give back the day of the week as text, such as "Friday".
    # Use read_date().
    return None


def is_weekend(text):
    # Give back True if the date text is a Saturday or a Sunday.
    # Hint: strftime("%A") gives the day name.
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Remember

Important

datetime.now() gives the time now. strftime() makes text from a date. strptime() makes a date from text. Both use format codes such as %d, %m and %Y.

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.