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
| Word | What it means | Example |
|---|---|---|
| datetime | A 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 code | A short code, such as %d, that stands 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") |
| String | Text inside quote marks. | "25/12/2026" |
| Function | A named piece of code that does one job. | len() |
| Validation | Checking that data is correct and 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
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.
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.
Text is only letters and digits. 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.
Worked example: the format codes
| Code | Stands for | Example for 25 December 2026, 9:30 am |
|---|---|---|
| %d | Day of the month, two digits | 25 |
| %m | Month as a number, two digits | 12 |
| %Y | Year, four digits | 2026 |
| %B | Month name in full | December |
| %A | Day of the week in full | Friday |
| %H | Hour on a 24 hour clock | 09 |
| %M | Minutes | 30 |
The cells students fill in are left blank in this preview.
Try it: date to text
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.
Quick check: format codes
Have a go
Quick check: format codes
4 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.
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.