๐Ÿ“…datetime, timedelta, strftime, timezone, UTCLESSON

Python datetime Module

Python's datetime module provides everything you need to work with dates and times: creation, formatting, parsing, arithmetic, and timezone handling.

Core Types

The module has four main types:

TypeDescription
datetime.datetimeCombined date and time
datetime.dateDate only (year, month, day)
datetime.timeTime only (hour, minute, second, microsecond)
datetime.timedeltaDuration between two points in time

Getting the Current Time

Naive vs Aware: A naive datetime has no timezone; an aware datetime carries a tzinfo object. Always prefer aware datetimes in production code to avoid subtle bugs when comparing or converting times.

timedelta โ€” Duration Arithmetic

timedelta represents a duration and supports arithmetic with datetime objects:

strftime โ€” Formatting Dates

strftime converts a datetime to a formatted string using format codes:

CodeMeaningExample
%Y4-digit year2024
%mMonth 01-1203
%dDay 01-3115
%HHour 00-2314
%MMinute 00-5930
%SSecond 00-5945
%AFull weekdayFriday
%BFull month nameMarch
%IHour 01-1202
%pAM/PMPM
%ZTimezone nameUTC

strptime โ€” Parsing Strings to datetime

strptime (string parse time) is the inverse of strftime:

If the format string doesn't match the input, you get a ValueError โ€” always wrap in try/except when parsing user input.

ISO 8601 โ€” fromisoformat and isoformat

Python 3.7+ supports ISO 8601 format directly:

ISO 8601 is the recommended format for storing or transmitting datetimes โ€” it's unambiguous and universally supported.

Timezone-Aware Datetimes with zoneinfo

Python 3.9 introduced the zoneinfo module (replaces the third-party pytz):

Comparing and Sorting Datetimes

Practical Example: Age Calculator

Knowledge Check

What is the difference between a 'naive' and an 'aware' datetime in Python?

Which strftime format code produces the full month name (e.g. 'March')?

What does timedelta(days=1, hours=12).total_seconds() return?