Lesson 4 of 6 · Modules and the Standard Library · 2 min read · Updated
Dates and times
Making dates, formatting them for people, reading them from text, and date arithmetic.
python
from datetime import date, datetime, timedelta
exam = date(2026, 3, 14)
print(exam)
print(exam.strftime("%d %B %Y"))
print(exam.strftime("%A"), exam.weekday())
due = exam + timedelta(days=30)
print(due)
print((date(2026, 12, 25) - exam).days)
Output
2026-03-14
14 March 2026
Saturday 5
2026-04-13
286
dateis a day;datetimeis a day plus a time.timedeltais a length of time. Add it to a date to move forward or back.- Subtracting two dates gives a timedelta;
.daysis the number of days. weekday()counts Monday as 0 and Sunday as 6.
Reading dates from text
python
from datetime import datetime
parsed = datetime.strptime("25-12-2026 18:30", "%d-%m-%Y %H:%M")
print(parsed)
print(parsed.hour, parsed.minute)
print(parsed.strftime("%I:%M %p"))
Output
2026-12-25 18:30:00
18 30
06:30 PM
strftime turns a date into text ("f" for format); strptime reads text into a date ("p" for parse). Both use the same codes: %d day, %m month number, %B month name, %Y year, %H 24-hour, %I 12-hour, %M minute, %p AM/PM, %A weekday.
python
from datetime import date, datetime
print(date.today()) # today's date
print(datetime.now()) # this moment, to the microsecond
Note
Indian forms usually write day first (25-12-2026); much software writes year first (2026-12-25), which also sorts correctly as text. Always say which format you expect.
Which function reads the text "05-06-2026" into a date?
Try this now
- Ask for a date of birth as DD-MM-YYYY and print the age in years and the weekday the person was born on.
- Print the dates of the next four Fridays from today.
Create a free account to save your progress, or sign in.