Skip to contentSkip to navigation

Module 11 · Lesson 02

Dates and Times

Work with calendars and clocks: create dates and datetimes, do arithmetic with timedelta, compare them, and turn them into text and back with strftime, strptime and ISO format.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Make and read dates
  • Add time with timedelta
  • Dates to text and back
  • Watch a book go overdue

Calendars in code

`datetime` knows how long each month is, when leap years fall and what day of the week a date is.

  • date

    date(2026, 7, 4) is one day. .year, .month and .day read its parts.

  • timedelta

    timedelta(days=10) is a length of time you can add or subtract.

  • Compare

    Dates compare with < and >, and subtracting two dates gives the gap between them.

  • Text

    strftime turns a date into text. strptime and fromisoformat read text back.

Dates everywhere

Almost every app needs to know when something happened or is due.

  • BirthdaysCount the days until your next birthday.
  • Daily rewardsCheck whether a whole day has passed since the last login.
  • BookingsA hotel adds the number of nights to the check-in date.
  • CalendarsFind which weekday the 1st of each month falls on.

Working out a due date

This line finds the date two weeks after another. Tap each part to see its job.

Part 1 of 5

Tap any part of the code below, or press Next.1 of 5 explored

result:A new date. start itself does not change.

Move through the calendar

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Make a date

A date has a year, a month and a day. Python checks that it really exists.

Your turn: Make the date of your birthday and print its weekday.

Python
from datetime import date
launch = date(2026, 7, 4)
print(launch)
print(launch.year, launch.month, launch.day)
print(launch.strftime("%A"))
Output
Press Run to see what it prints.

Watch a library book go overdue

Press Step to run one line at a time. Watch the names box change.

Ready. Press Step to run the first line.

  1. from datetime import date, timedelta
  2. borrowed = date(2026, 3, 25)
  3. due = borrowed + timedelta(days=14)
  4. returned = date(2026, 4, 10)
  5. late = (returned - due).days
  6. print("Due", due)
  7. print("Days late:", late)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.The day after New Year's Eve:

from datetime import date, timedelta
print(date(2026, 12, 31) + timedelta(days=1))

0 of 6 answered

Common date misconceptions

Each card is something learners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

The main types

The datetime module provides a few types. The two you will use most are date, a calendar day, and datetime, a day plus a time of day:

Try it 1: edit me, then Run
from datetime import date, datetime

launch = date(2024, 3, 15)
meeting = datetime(2024, 3, 15, 14, 30)
print(launch)                       # 2024-03-15
print(meeting)                      # 2024-03-15 14:30:00
print(launch.year, launch.month, launch.day)   # 2024 3 15
print(meeting.hour, meeting.minute)            # 14 30
Output
Press Run to see what it prints.

Arguments go from the largest unit to the smallest: year, month, day, then hour, minute, second. Python checks them, so date(2024, 2, 30) raises ValueError: day is out of range for month. The odd naming, a module called datetime containing a class also called datetime, is why most code writes from datetime import date, datetime, timedelta.

date.today() and datetime.now() give the current date and time. They are useful in real programs, but their values change every time you run the code, so the examples here use fixed dates.

Doing date arithmetic with timedelta

A timedelta is a length of time. Adding it to a date moves the date; subtracting two dates gives a timedelta:

Try it 2: edit me, then Run
from datetime import date, timedelta

borrowed = date(2024, 1, 28)
due = borrowed + timedelta(days=21)
print(due)                          # 2024-02-18

gap = date(2024, 12, 25) - date(2024, 11, 26)
print(gap.days)                     # 29
Output
Press Run to see what it prints.

The calendar rules are handled for you: crossing month ends, year ends and leap days all just work. timedelta accepts weeks, days, hours, minutes and seconds; it has no months or years, because those have no fixed length. A timedelta between two datetimes can be turned into seconds with total_seconds().

Comparing and sorting

Dates compare in time order with the usual operators, so date(2024, 1, 5) < date(2024, 2, 1) is True, and sorted and min/max put dates in chronological order. Do not compare a date with a datetime; convert one first, for example with meeting.date().

weekday() gives the day of the week as a number from Monday 0 to Sunday 6:

Try it 3: edit me, then Run
print(date(2024, 3, 16).weekday())  # 5, a Saturday
Output
Press Run to see what it prints.

Dates to text: strftime

strftime (string from time) formats a date using codes that start with %:

Code Meaning Example
%Y four-digit year 2024
%m month, two digits 03
%d day, two digits 05
%B / %b month name, full or short March / Mar
%A / %a weekday name, full or short Tuesday / Tue
%H:%M hour and minute, 24-hour clock 14:30
Try it 4: edit me, then Run
d = datetime(2024, 3, 5, 14, 30)
print(d.strftime("%d/%m/%Y"))          # 05/03/2024
print(d.strftime("%A %d %B, %H:%M"))   # Tuesday 05 March, 14:30
Output
Press Run to see what it prints.

Everything that is not a code, such as slashes, spaces and commas, is copied as it is.

Text to dates: strptime

strptime (string parse time) does the reverse: you describe the format the text is in, and get back a datetime:

Try it 5: edit me, then Run
text = "15/03/2024 09:45"
when = datetime.strptime(text, "%d/%m/%Y %H:%M")
print(when.year, when.hour)            # 2024 9
print(when.date())                     # 2024-03-15
Output
Press Run to see what it prints.

The format must match the text exactly. If it does not, or the date does not exist, strptime raises ValueError, which you can catch like any other. This strictness matters: 03/04/2024 means 3 April in most of the world and 4 March in the United States, and only you know which format your data uses.

ISO format: the safe default

The international standard ISO 8601 writes dates largest unit first: 2024-03-15, or 2024-03-15T14:30:00 with a time. It is unambiguous, it sorts correctly even as plain text, and Python reads and writes it directly:

Try it 6: edit me, then Run
print(date(2024, 3, 15).isoformat())       # 2024-03-15
print(date.fromisoformat("2024-03-15"))    # 2024-03-15
Output
Press Run to see what it prints.

When you store dates in files, such as JSON or CSV, use ISO strings. Convert to friendlier formats only when showing dates to people.

A word on time zones

The datetimes in this lesson are naive: they carry no time zone, so 14:30 means 14:30 wherever the reader is. That is fine for a diary or a school timetable. Programs that coordinate people in different countries need aware datetimes, which record their time zone. The Python in Depth course covers them; for now, be aware that datetime.now() returns your computer's local time.

Syntax

The general shape of the statements in this lesson.

syntax.py
from datetime import date, datetime, timedelta
date(2024, 3, 15)                       # a calendar day
datetime(2024, 3, 15, 14, 30)           # day and time
d + timedelta(days=7)                   # move a date
(d2 - d1).days                          # days between
d.weekday()                             # Monday 0 ... Sunday 6
d.strftime("%d %B %Y")                  # date -> text
datetime.strptime("15/03/2024", "%d/%m/%Y")   # text -> datetime
d.isoformat() / date.fromisoformat("2024-03-15")
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

Library due dates

Beginner

Books are lent for 21 days. For each loan, work out the due date, and report how many days overdue it is on a given day, or how many days are left.

Python
from datetime import date, timedelta

LOAN = timedelta(days=21)
today = date(2024, 3, 1)
loans = [("Emma", date(2024, 2, 1)), ("Dune", date(2024, 2, 15)), ("Ulysses", date(2024, 2, 9))]

for title, borrowed in sorted(loans, key=lambda loan: loan[1]):
    due = borrowed + LOAN
    days = (due - today).days
    if days < 0:
        status = f"{-days} days overdue"
    else:
        status = f"{days} days left"
    print(f"{title}: due {due.strftime('%d %b')}, {status}")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

Adding a timedelta gives each due date, crossing from February into March correctly, including the leap day in 2024. Subtracting dates gives a timedelta whose days can be negative. Sorting by the borrowed date works because dates compare in time order.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Doing date maths with numbers

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
day, month = 30, 1
day = day + 5
print(day, month)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints 35 1, a day that does not exist

Write this instead

from datetime import date, timedelta
print(date(2024, 1, 30) + timedelta(days=5))

Why it happens

Plain numbers know nothing about month lengths or leap years.

In the real world

Where this shows up in software people use every day.

  1. Planning a delivery date

    E-commerce

    An online shop promises delivery in three working days. Orders placed after 2 pm count from the next day, and weekends are skipped.

    Why Python fits

    strptime reads each order time, the hour decides the start day, and weekday() < 5 counts only Monday to Friday. All the calendar knowledge comes from the datetime module, so month ends and leap years need no special code.

    Python
    from datetime import datetime, timedelta
    
    def delivery_date(ordered, working_days=3):
        day = ordered.date()
        if ordered.hour >= 14:
            day += timedelta(days=1)
        added = 0
        while added < working_days:
            day += timedelta(days=1)
            if day.weekday() < 5:
                added += 1
        return day
    
    orders = ["2024-03-13 10:15", "2024-03-14 16:40", "2024-03-15 09:00"]
    for text in orders:
        ordered = datetime.strptime(text, "%Y-%m-%d %H:%M")
        print(ordered.strftime("%a %H:%M"), "->", delivery_date(ordered).strftime("%A %d %B"))
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

How do I add a month?

timedelta has no months, because months differ in length. Decide what "a month later" means for your program, for example the same day number in the next month, and build it with date(year, month + 1, day), handling December and short months yourself.

Why does my weekday name come out in English?

strftime uses the language of the computer's locale, which is English by default in most setups, including the PyLabs runner.

How do I measure how long something took?

Subtract two datetimes, as in finished - started, and read the timedelta's total_seconds(). For timing code very precisely, the time module's perf_counter is better, because it is not affected by clock changes.

Can I compare a datetime with a date?

No, Python refuses to order them. Use datetime.date() to drop the time, or datetime.combine(d, time()) to add midnight to a date.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 9 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.