Skip to content
Kuza Ndoto Academy

Dates & Times

Beginner → IntermediateChapter 9 · Page 51 of 565 min readUpdated 15 Nov 2026

Programs constantly deal with dates and times: due dates, birthdays, opening hours, transaction timestamps. Python's datetime module lets you create, format, parse, compare and do arithmetic with them reliably.

The main types

TypeStoresExample
dateYear, month, daydate(2026, 3, 14)
timeHour, minute, second, microsecondtime(9, 30)
datetimeA date and a time togetherdatetime(2026, 3, 14, 9, 30)
timedeltaA length of time (duration)timedelta(days=7)
timezone / zoneinfo.ZoneInfoTime zone informationZoneInfo("Africa/Nairobi")

Creating dates and datetimes

from datetime import date, datetime

exam_day = date(2026, 3, 14)
print(exam_day)
print(exam_day.year, exam_day.month, exam_day.day)
print(exam_day.weekday())        # Monday is 0, Sunday is 6

start = datetime(2026, 3, 14, 9, 30)
print(start)
print(start.date(), start.hour, start.minute)
2026-03-14 2026 3 14 5 2026-03-14 09:30:00 2026-03-14 9 30

To get the current date and time, use date.today() and datetime.now(). Their output depends on when you run them, so this is just an example:

from datetime import date, datetime

print(date.today())
print(datetime.now())
2026-11-15 2026-11-15 14:07:52.318406

Formatting with strftime

strftime() ("string format time") turns a date into text in any layout you choose, using format codes:

CodeMeaningExample
%dDay of month, two digits14
%mMonth number, two digits03
%Y / %yYear with century / without2026 / 26
%B / %bMonth name, full / shortMarch / Mar
%A / %aWeekday name, full / shortSaturday / Sat
%H / %IHour, 24-hour / 12-hour clock09
%M / %SMinutes / seconds30 / 00
%pAM or PMAM
from datetime import datetime

start = datetime(2026, 3, 14, 9, 30)
print(start.strftime("%d/%m/%Y %H:%M"))
print(start.strftime("%A, %d %B %Y"))
print(start.strftime("%I:%M %p"))
print(f"Exam: {start:%a %d %b at %H:%M}")    # format codes work in f-strings too
14/03/2026 09:30 Saturday, 14 March 2026 09:30 AM Exam: Sat 14 Mar at 09:30

Month and day names follow your computer's language settings; on most systems they appear in English as shown.

Parsing text with strptime

datetime.strptime() ("string parse time") does the reverse: it reads text in a known format and builds a datetime. The format string must match the text exactly.

from datetime import datetime

party = datetime.strptime("25/12/2026 18:45", "%d/%m/%Y %H:%M")
print(party)
print(party.strftime("%A"))

stamp = datetime.fromisoformat("2026-03-14T09:30:00")   # ISO 8601 text
print(stamp.isoformat())
2026-12-25 18:45:00 Friday 2026-03-14T09:30:00

If the text doesn't match the format, strptime raises a ValueError, which you can handle with try/except.

Date arithmetic with timedelta

Add or subtract a timedelta to move dates forward or back. Subtracting two dates gives a timedelta.

from datetime import date, datetime, timedelta

today = date(2026, 3, 14)
print(today + timedelta(days=30))         # a loan due in 30 days
print(today - timedelta(weeks=2))

holiday = date(2026, 12, 25)
gap = holiday - today
print(gap)
print(gap.days, "days until Christmas")

shift_start = datetime(2026, 3, 14, 8, 30)
shift_end = datetime(2026, 3, 14, 17, 15)
worked = shift_end - shift_start
print(worked)
print(worked.total_seconds() / 3600, "hours")
2026-04-13 2026-02-28 286 days, 0:00:00 286 days until Christmas 8:45:00 8.75 hours

Dates compare naturally, so you can use <, > and ==, and loop over a range of days:

from datetime import date, timedelta

start = date(2026, 3, 14)
for i in range(3):
    day = start + timedelta(days=i)
    print(day.strftime("%a %d %b"))

deadline = date(2026, 3, 20)
print(start < deadline)
Sat 14 Mar Sun 15 Mar Mon 16 Mar True

A common real task is calculating someone's age. Comparing (month, day) tuples tells you whether this year's birthday has happened yet:

from datetime import date

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

print(age_on(date(2004, 8, 20), date(2026, 3, 14)))
print(age_on(date(2004, 8, 20), date(2026, 8, 20)))
21 22
Note

timedelta works in days, seconds and microseconds; it has no "months" option because months have different lengths. To add calendar months, change the month value yourself (watching for year changes and short months) or use a third-party package such as python-dateutil.

Time zones

A datetime without time zone information is called naive; one with it is aware. For anything involving users in different countries, store aware datetimes. The zoneinfo module provides real time zones by name.

from datetime import datetime
from zoneinfo import ZoneInfo

meeting = datetime(2026, 3, 14, 9, 30, tzinfo=ZoneInfo("Africa/Nairobi"))
print(meeting)
print(meeting.astimezone(ZoneInfo("Europe/London")))
print(meeting.astimezone(ZoneInfo("Africa/Lagos")))
2026-03-14 09:30:00+03:00 2026-03-14 06:30:00+00:00 2026-03-14 07:30:00+01:00

East Africa Time is three hours ahead of UTC all year round. London switches to summer time later in March, so the gap would shrink to two hours after that.

Common mistake

On Windows, ZoneInfo("Africa/Nairobi") can fail with ZoneInfoNotFoundError because Windows doesn't include the time zone database Python needs. Install it with python -m pip install tzdata (see pip & virtual environments).

Warning

datetime.utcnow() is deprecated since Python 3.12 because it returns a naive datetime that is easy to misread. Use datetime.now(timezone.utc) (with from datetime import timezone) to get the current UTC time as an aware datetime. Also, don't compare naive and aware datetimes: Python raises a TypeError.

Tip

When saving dates to files or sending them to APIs, use the ISO 8601 format with isoformat(), and read them back with fromisoformat(). ISO dates such as 2026-03-14 also sort correctly as plain text.

Key points

  • Use date, time, datetime and timedelta from the datetime module.
  • strftime formats dates as text; strptime parses text into dates.
  • Add a timedelta to move dates; subtract dates to get a duration.
  • Use zoneinfo.ZoneInfo for time zones, and avoid the deprecated utcnow().
Up next · New chapter: Projects & PracticeProject: Budget TrackerTrack income and spending in the terminal.
→

Tip: use the ← and → keys to move between pages.