CodeMIRAI
0 XP

Dates and times

2 min read 5 runnable examples Quiz included

The datetime module handles dates, times and the differences between them.

Dates and datetimes

Python
from datetime import date, datetime

launch = date(2026, 3, 15)
print(launch)
print(launch.year, launch.month, launch.day)
print(launch.strftime("%A"))          # day of the week

meeting = datetime(2026, 3, 15, 14, 30)
print(meeting)
print(meeting.hour, meeting.minute)

date.today() and datetime.now() give the current date and time.

Date arithmetic with timedelta

A timedelta is a length of time. Add it to a date to move forwards or backwards:

Python
from datetime import date, timedelta

start = date(2026, 1, 25)
print(start + timedelta(days=10))
print(start - timedelta(weeks=2))

deadline = date(2026, 4, 1)
remaining = deadline - start            # subtracting dates gives a timedelta
print(remaining.days, "days to go")

How old is someone?

Python
from datetime import date

def age_on(birthday, on_date):
    years = on_date.year - birthday.year
    had_birthday = (on_date.month, on_date.day) >= (birthday.month, birthday.day)
    return years if had_birthday else years - 1

print(age_on(date(2004, 8, 20), date(2026, 8, 19)))
print(age_on(date(2004, 8, 20), date(2026, 8, 20)))

Comparing (month, day) tuples checks whether the birthday has happened yet this year.

Formatting with strftime

strftime ("string format time") turns a date into text using codes:

Python
from datetime import datetime

moment = datetime(2026, 10, 29, 9, 5)
print(moment.strftime("%d/%m/%Y"))            # 29/10/2026
print(moment.strftime("%B %d, %Y"))           # October 29, 2026
print(moment.strftime("%a %H:%M"))            # Thu 09:05
print(moment.strftime("%I:%M %p"))            # 09:05 AM
print(moment.isoformat())                     # 2026-10-29T09:05:00
CodeMeaningExample
%Y4-digit year2026
%mmonth as a number10
%dday of the month29
%B / %bmonth name / shortOctober / Oct
%A / %aweekday / shortThursday / Thu
%H / %Ihour, 24h / 12h09
%Mminutes05
%pAM or PMAM

Parsing with strptime

strptime ("string parse time") does the reverse: text to a datetime, using the same codes:

Python
from datetime import datetime

text = "15-08-2026 18:45"
when = datetime.strptime(text, "%d-%m-%Y %H:%M")
print(when, when.strftime("%A"))
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.