Skip to main content
Module 8 · Lesson 2 of 430/36 in the course~16 min
Module lessons (2/4)

datetime: dates and times

Lesson preview5 hands-on exercises readyPython Course · Module 8 — Essential standard library

date/time/datetime/timedelta, strftime formatting, strptime parsing, ISO 8601, and date arithmetic.

What you'll learn in this lesson

  • Choose the right class in the datetime form: date, time, datetime, and timedelta.
  • Perform arithmetic on dates and durations with timedelta calculating deadlines and differences in days or seconds.
  • Format and parse dates explicitly with strftime() and strptime(), in addition to the ISO 8601 standard.
  • Avoid the most common errors between naive, aware (timezone.utc), and timedelta bounds.

Overview

Working with dates and times by hand using strings or multiplication by 86400 is a sure source of bugs (leap years, time changes, 28/30/31 day months). The datetime module offers dedicated immutable types that automatically handle all calendar rules.

Always distinguish an instant (date or datetime, precise point on the timeline) from a duration (timedelta, relative distance between two instants): subtracting two instants produces a duration; adding a duration to an instant produces a new instant.

Sections covered in this lesson

  1. 11. Construct instants and manage the current time
  2. 22. Safe time arithmetic with timedelta
  3. 33. Formatting (strftime) and parsing (strptime)
  4. 44. Data exchange with ISO 8601 (isoformat / fromisoformat)
  5. 5Check for understanding
  6. 6Test yourself
Pro Lesson · Module 8 — Essential standard library

Unlock "datetime: dates and times" and the full Python Course curriculum

date/time/datetime/timedelta, strftime formatting, strptime parsing, ISO 8601, and date arithmetic.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Python Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.