IntermediateLesson 17 of 306 min read

Dates and times with datetime

Create, format, parse and calculate with dates, times, durations and time zones using the datetime module.

In this lesson you will

  • Create and format dates and times
  • Parse text into dates
  • Calculate with timedelta
  • Handle time zones sensibly

About 21 minutes

Time is harder than it looks

How many days until your exam? When does this subscription expire? Show “posted 3 hours ago”. Sort these events. Schedule a reminder next Monday. Time is full of awkward rules: months of different lengths, leap years, time zones and daylight saving. Python’s datetime module does the hard arithmetic for you. This lesson teaches the handful of tools you need.

Dates and times right now

from datetime import date, datetime, time

d = date(2026, 3, 15)
print(d)
print(d.year, d.month, d.day)
print(d.weekday(), d.strftime("%A"))      # Monday is 0

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

t = time(9, 45)
print(t)
2026-03-15
2026 3 15
6 Sunday
2026-03-15 14:30:05
14 30
09:45:00
Good to know

date.today() and datetime.now() give you the current moment. Their output changes every time you run them, so the examples here build specific dates to keep the output predictable.

from datetime import date, datetime
today = date.today()
print(type(today).__name__, today.year >= 2025)
now = datetime.now()
print(type(now).__name__, now.hour in range(24))
date True
datetime True

Formatting dates: strftime

from datetime import datetime

dt = datetime(2026, 3, 5, 9, 7)
print(dt.strftime("%d/%m/%Y"))
print(dt.strftime("%B %d, %Y"))
print(dt.strftime("%A, %I:%M %p"))
print(dt.strftime("%Y-%m-%d %H:%M"))
print(dt.isoformat())
05/03/2026
March 05, 2026
Thursday, 09:07 AM
2026-03-05 09:07
2026-03-05T09:07:00
Code Meaning Example
%Y 4-digit year 2026
%m month number 03
%d day 05
%B / %b month name March / Mar
%A / %a weekday name Thursday / Thu
%H : %M : %S 24-hour clock 09:07:00
%I %p 12-hour clock 09 AM

Parsing dates: strptime

from datetime import datetime

dt = datetime.strptime("15/08/2026 18:45", "%d/%m/%Y %H:%M")
print(dt)
print(dt.strftime("%A"))

d = datetime.fromisoformat("2026-08-15T18:45:00")
print(d.date())

try:
    datetime.strptime("31/02/2026", "%d/%m/%Y")
except ValueError as e:
    print("Not a real date:", e)
2026-08-15 18:45:00
Saturday
2026-08-15
Not a real date: day is out of range for month

strftime (f for format) goes from date to text. strptime (p for parse) goes from text to date. The format string tells Python how to read the text, and impossible dates such as 31 February raise ValueError.

Arithmetic with timedelta

from datetime import date, datetime, timedelta

exam = date(2026, 6, 1)
start = date(2026, 3, 15)
print("Days to study:", (exam - start).days)

print(start + timedelta(days=30))
print(start - timedelta(weeks=2))

meeting = datetime(2026, 3, 15, 10, 0)
print(meeting + timedelta(hours=2, minutes=30))

delta = datetime(2026, 3, 16, 9, 0) - datetime(2026, 3, 15, 8, 30)
print(delta, delta.total_seconds() / 3600, "hours")
Days to study: 78
2026-04-14
2026-03-01
2026-03-15 12:30:00
1 day, 0:30:00 24.5 hours

Comparing and sorting

from datetime import date

events = [("Exam", date(2026, 6, 1)), ("Trip", date(2026, 4, 10)), ("Birthday", date(2026, 5, 3))]
for name, when in sorted(events, key=lambda e: e[1]):
    print(when, name)

print(date(2026, 4, 10) < date(2026, 5, 3))
2026-04-10 Trip
2026-05-03 Birthday
2026-06-01 Exam
True

Real tasks

from datetime import date

def age(born, today):
    years = today.year - born.year
    if (today.month, today.day) < (born.month, born.day):
        years -= 1
    return years

print(age(date(2000, 8, 20), date(2026, 3, 15)))
print(age(date(2000, 3, 15), date(2026, 3, 15)))
25
26
from datetime import date, timedelta
import calendar

d = date(2026, 3, 15)
next_monday = d + timedelta(days=(7 - d.weekday()) % 7 or 7)
print(next_monday, next_monday.strftime("%A"))

print(calendar.isleap(2028))
print(calendar.monthrange(2026, 2)[1], "days in Feb 2026")

first_of_month = d.replace(day=1)
print(first_of_month)
2026-03-16 Monday
True
28 days in Feb 2026
2026-03-01

Time zones

from datetime import datetime, timezone, timedelta
from zoneinfo import ZoneInfo

utc = datetime(2026, 3, 15, 12, 0, tzinfo=timezone.utc)
print(utc)
print(utc.astimezone(ZoneInfo("Asia/Karachi")))
print(utc.astimezone(ZoneInfo("America/New_York")))
print(utc.timestamp())
2026-03-15 12:00:00+00:00
2026-03-15 17:00:00+05:00
2026-03-15 08:00:00-04:00
1773576000.0
A golden rule

Store and calculate times in UTC, and convert to the user’s local time zone only when displaying. This avoids a whole class of daylight-saving bugs.

Common mistake

Mixing “naive” and “aware” datetimes. A datetime without a time zone (naive) cannot be compared or subtracted with one that has a time zone (aware): Python raises TypeError. Decide for each project and be consistent.

Timing your code

import time

start = time.perf_counter()
total = sum(range(1_000_000))
elapsed = time.perf_counter() - start
print("Finished:", total)
print("Fast enough:", elapsed < 5)
Finished: 499999500000
Fast enough: True
Practice

Print how many days remain from 2026-03-15 until 2026-12-25, and the weekday of Christmas that year.

Show one possible answer
from datetime import date

start = date(2026, 3, 15)
xmas = date(2026, 12, 25)
print((xmas - start).days, "days")
print(xmas.strftime("%A"))
285 days
Friday
Practice

Write a function deadlines(start, days) that returns the dates 7, 14 and 21 days after a start date, formatted like “25 Mar 2026”.

Hint: timedelta(days=n) and strftime(“%d %b %Y”).

Show one possible answer
from datetime import date, timedelta

def deadlines(start):
    return [(start + timedelta(days=n)).strftime("%d %b %Y") for n in (7, 14, 21)]

print(deadlines(date(2026, 3, 18)))
['25 Mar 2026', '01 Apr 2026', '08 Apr 2026']
Use libraries for complex schedules

For recurring events, such as every second Tuesday, the third-party dateutil package makes the maths simple.

Worked example: a subscription reminder

Let us combine parsing, formatting and arithmetic in one realistic job. A small service stores each customer’s start date as text. We need to work out when each subscription ends and how many days are left on a chosen day, then flag the ones that expire soon. Read the code first and say in plain words what each line does.

from datetime import datetime, timedelta

customers = [
    ("Sara", "2026-01-10", 30),
    ("Ali", "2026-02-20", 365),
    ("Mina", "2026-03-01", 14),
]

today = datetime.strptime("2026-03-12", "%Y-%m-%d").date()

for name, start_text, days in customers:
    start = datetime.strptime(start_text, "%Y-%m-%d").date()
    end = start + timedelta(days=days)
    left = (end - today).days
    if left < 0:
        status = f"expired {-left} days ago"
    elif left <= 7:
        status = f"ends in {left} days: send a reminder"
    else:
        status = f"{left} days left"
    print(f"{name:<5} ends {end.strftime('%d %b %Y')}  {status}")
Sara  ends 09 Feb 2026  expired 31 days ago
Ali   ends 20 Feb 2027  345 days left
Mina  ends 15 Mar 2026  ends in 3 days: send a reminder

Three ideas did all the work. strptime turned text into a real date. Adding a timedelta found the end date. Subtracting two dates gave a timedelta whose .days told us how long remained. Notice we fixed today to a known date so the output is predictable; in a live program you would use date.today().

Compare dates, not text

Never compare dates as strings in a format like 12/03/2026: text sorts by its first characters, so 05/12/2026 would come before 12/01/2025. Convert to real dates first. The one exception is the ISO format 2026-03-12, which happens to sort correctly as text.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does subtracting two dates give?

  1. A string
  2. An integer only
  3. A timedelta
  4. A list

The result is a timedelta with .days.

Which method turns a date into formatted text?

  1. strftime
  2. strptime
  3. parse
  4. format_date

f stands for format.

What does %Y-%m-%d produce for 5 March 2026?

  1. 05-03-2026
  2. March 5
  3. 2026-03-05
  4. 2026-5-3

Year-month-day with zero padding.

What is a good practice for storing times?

  1. Store in UTC, convert for display
  2. Store local text
  3. Store only hours
  4. Never store times

UTC avoids daylight-saving confusion.

What does datetime.strptime("31/02/2026", "%d/%m/%Y") do?

  1. Returns 3 March
  2. Raises ValueError
  3. Returns None
  4. Returns today

31 February does not exist.

Summary

  • date, time and datetime hold moments.
  • strftime formats; strptime parses.
  • Subtracting dates gives a timedelta.
  • Store UTC, display local time.

Next lesson

Next: comprehensions, generators and iterators, writing Python the Pythonic way.

Questions

How do I get today's date?

from datetime import date; date.today().

Which format code is minutes and which is month?

%M is minutes and %m is month. Capital letters usually mean time; lowercase usually mean date.

Is there an easier library?

Yes, third-party packages like arrow and pendulum, but the standard datetime covers most needs.

Progress is saved in this browser.