Skip to content

Beginning of the lesson

Dates and Times

Model real moments in code: build them, do arithmetic on them, and turn them into text and back

Big idea: Time looks simple to a human but is full of traps for a program — months of different lengths, leap years, and clocks that jump for daylight saving. Python's datetime module gives you real objects that understand all of this, so you stop juggling raw numbers and strings by hand.
By the end you will be able to:
  • create date, time and datetime objects and read their fields,
  • measure and shift time with timedelta,
  • turn a datetime into text with strftime and read text back with strptime,
  • explain the difference between a naive and an aware datetime, and attach a time zone.

1. Why time is harder than it looks

Think of a specific moment — say, the instant a train leaves. To pin it down you need a calendar part (which day) and a clock part (which time of day), and sometimes a third thing: where on Earth that clock is running. Two people can say "3 o'clock" and mean moments hours apart.

Analogy: a plain number like 1500 is like a photo with no caption — is it minutes, a year, a price? A datetime object is the same photo with a caption: it knows 1500 means the year, that 30 is a valid minute but not a valid month, and that adding one day to 31 January lands on 1 February, not 32 January. That built-in knowledge is exactly why we prefer objects over doing date maths on bare integers.

If you try to store a date as a string like "2026-07-15" and then ask "what is 45 days later?", you are stuck — strings do not do arithmetic. Convert to a datetime first, do the maths, then convert back to a string when you need to show it.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers