Dates & Times (datetime)

Almost every real program deals with time: when an order was placed, how old an account is, what to schedule next. Python's datetime module gives you proper date objects you can compare, format, and do arithmetic with — far safer than juggling strings.

Learn Dates & Times (datetime) in our free Python course — a beginner-friendly interactive lesson with runnable examples, a practice exercise and a quick…

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

In this lesson you'll create dates, format them for humans, parse them back from text, and calculate durations.

You could store "2024-01-15" as a plain string. But the moment you need to ask "is this date before that one?" or "how many days until then?", strings fall apart. Comparing "2024-1-9" and "2024-1-10" as text gives the wrong answer because text sorts character by character.

Real date objects know they're dates and behave correctly:

Every attribute is a plain integer, so you can use them in conditions, f-strings, and calculations directly.

A raw datetime prints as 2024-01-15 14:32:08 . To control the look, use strftime with format codes:

Data arrives as text — from forms, CSVs, APIs. strptime turns a string into a real datetime by telling Python the exact layout:

Memory trick: strf time goes datetime → string (formatting), str p time goes string → datetime (parsing).

A timedelta represents a span of time . Add it to a date to move forward or back; subtract two dates to get the gap between them:

This is the kind of logic that powers billing dashboards and "account created 3 months ago" labels:

Notice the age trick: comparing the (month, day) tuples handles the "has their birthday happened yet this year?" question in one clean line.

A datetime without timezone info is called naive — it doesn't know which timezone it belongs to. For anything user-facing, work with aware datetimes:

These lines should print how many days until a deadline, but they're shuffled. Find the right order:

Import first, build both datetimes, subtract to get a timedelta, then read its .days attribute.

False — Feb 1 comes after Jan 31, so it is NOT less than it. Date objects compare chronologically, unlike strings.

July — %B is the full month name. ( %b would give the short form, "Jul".)

2024-02-01 — timedelta correctly rolls over the month boundary. You never have to think about how many days are in January.

You can now bend time to your will!

You can create dates, format them with strftime, parse text with strptime, do arithmetic with timedelta, and handle timezones safely. These are skills you'll use in nearly every project that touches the real world.

🚀 Up next: Working with JSON — the data format that powers almost every web API and config file.

Practice quiz

Which datetime class holds ONLY a calendar date (year, month, day)?

  • time
  • datetime
  • date
  • timedelta

Answer: date. date holds just year/month/day; datetime combines date and time; timedelta is a duration.

Which class represents a duration like '3 days' or '2 hours'?

  • timedelta
  • date
  • time
  • datetime

Answer: timedelta. timedelta represents a span of time you can add to or subtract from dates.

How do you get the current date and time?

  • date.today()
  • datetime.current()
  • time.now()
  • datetime.now()

Answer: datetime.now(). datetime.now() returns the current local date and time; date.today() gives just the date.

What does strftime do?

  • Parses a string into a datetime
  • Formats a datetime into a text string
  • Adds days to a date
  • Compares two dates

Answer: Formats a datetime into a text string. strftime ('string FROM time') formats a datetime into text using codes like %Y-%m-%d.

Which function parses text INTO a datetime object?

  • strptime
  • strftime
  • isoformat
  • fromtext

Answer: strptime. strptime ('string parse time') reads a string into a datetime, given a matching format.

What does datetime(2024, 7, 4).strftime('%B') return?

  • '07'
  • 'Jul'
  • 'July'
  • 'Thursday'

Answer: 'July'. %B is the full month name, so it returns 'July' (%b would give 'Jul').

What does datetime(2024, 1, 31) + timedelta(days=1) give?

  • 2024-01-32
  • 2024-02-01
  • an error
  • 2024-01-31

Answer: 2024-02-01. timedelta correctly rolls over the month boundary, giving 2024-02-01.

What does (date(2024, 1, 10) - date(2024, 1, 9)).days return?

  • 0
  • -1
  • an error
  • 1

Answer: 1. Subtracting two dates gives a timedelta; its .days is 1.

Why store dates in UTC?

  • It is faster
  • UTC has no daylight-saving shifts and is unambiguous worldwide
  • It uses less memory
  • It is required by Python

Answer: UTC has no daylight-saving shifts and is unambiguous worldwide. UTC avoids DST ambiguity; store/compute in UTC and convert to local time only for display.

What error comes from mixing naive and aware datetimes in subtraction?

  • ValueError
  • KeyError
  • TypeError: can't subtract offset-naive and offset-aware datetimes
  • It works fine

Answer: TypeError: can't subtract offset-naive and offset-aware datetimes. You can't subtract a naive (no timezone) datetime from an aware one; it raises a TypeError.