Module lessons (2/4)
datetime: dates and times
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
datetimeform:date,time,datetime, andtimedelta. - Perform arithmetic on dates and durations with
timedeltacalculating deadlines and differences in days or seconds. - Format and parse dates explicitly with
strftime()andstrptime(), in addition to the ISO 8601 standard. - Avoid the most common errors between naive, aware (
timezone.utc), andtimedeltabounds.
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
- 11. Construct instants and manage the current time
- 22. Safe time arithmetic with
timedelta - 33. Formatting (
strftime) and parsing (strptime) - 44. Data exchange with ISO 8601 (
isoformat/fromisoformat) - 5Check for understanding
- 6Test yourself
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.