← Python lessons

Python datetime: Dates, Times and Comparing Them

Python's datetime module stores a calendar day as a date and a day plus a clock time as a datetime. You can read their parts, compare them and sort them.

Read Importing modules first.

Make a date

Import date from the datetime module. Give it the year, month and day, in that order.

from datetime import date

launch = date(2026, 3, 14)
print(launch)
print(launch.year, launch.month, launch.day)

Printing a date shows it year first: 2026-03-14. The parts are plain numbers you can read with .year, .month and .day.

Make a date with a time

A datetime adds hours and minutes after the day. Hours use the 24-hour clock.

from datetime import datetime

kickoff = datetime(2026, 3, 14, 18, 30)
print(kickoff)
print(kickoff.hour, kickoff.minute)
print(kickoff.date())

18, 30 is 6:30 in the evening. .date() drops the time and keeps the day.

Get today's date and the current time

date.today() and datetime.now() read the clock of the computer running the code.

from datetime import date, datetime

print(date.today())
print(datetime.now())

Run it twice: the time changes every run. Programs that must give the same answer every time use a fixed date instead.

Compare two dates

Compare dates with <, > and ==, just like numbers. An earlier date is smaller.

from datetime import date

due = date(2026, 5, 1)
handed_in = date(2026, 4, 28)
print(handed_in < due)
print(handed_in == due)

handed_in comes before due, so the first line is True.

Find the earliest date and sort dates

Because dates compare, min(), max() and sorted() work on them too.

from datetime import date

birthdays = [date(2012, 9, 3), date(2011, 12, 25), date(2012, 1, 7)]
print(min(birthdays))
for day in sorted(birthdays):
    print(day)

min() finds the oldest birthday. sorted() puts them in calendar order.

Note: Write date(2026, 3, 14), not date(2026, 03, 14): a leading zero is a SyntaxError. Compare a date with a date and a datetime with a datetime — mixing them with < raises TypeError.

See also: Days between two dates, Format and parse dates, Sorting.

Your turn

Print whether match_day is before deadline, then print the month of match_day.

from datetime import date

deadline = date(2026, 6, 30)
match_day = date(2026, 6, 12)
# add two prints: is match_day before deadline, then match_day's month

Expected output

True
6

Practise this in the free Python course, where every exercise checks your code instantly.