Calendar dates
Represent a calendar day without a clock component.
Python · Module
Python’s datetime module supplies standard-library types for dates, times, combined timestamps, durations, and time zones. It supports arithmetic, field extraction, conversion, and explicit string formatting.
The module provides date, time, combined datetime, duration, and timezone-related types. These objects support arithmetic, attribute access, conversion, and formatting for common backend and scripting tasks.
import datetime
class datetime.date
class datetime.time
class datetime.datetime
class datetime.timedelta
class datetime.tzinfo
class datetime.timezone| Name | Type | Description |
|---|---|---|
format | str | Format string controlling the textual representation. |
The module contains temporal classes; individual constructors and methods return the objects or strings described by their respective documentation.
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
print(now.isoformat())
Creates an aware UTC datetime and formats it as an ISO 8601 string.
Represent a calendar day without a clock component.
Record an instant with an explicit UTC offset.
Compute elapsed or scheduled intervals.
Render temporal values for logs, APIs, or reports.
The module supplies classes for dates, times, combined datetimes, durations, and timezone information. A datetime combines a date and a time, while timedelta represents a duration between date or datetime values.
Follow-up: How would you produce a UTC timestamp? Use an aware datetime with a UTC tzinfo, such as datetime.now(timezone.utc), rather than relying on a local naive value.
date represents a calendar date, time represents a time independent of a particular day, and datetime combines both. timedelta expresses a duration at microsecond resolution.
Follow-up: Why might date be preferable to datetime? It avoids carrying an irrelevant clock and timezone component when only calendar-day operations are required.
strftime(format) creates a formatted string under control of an explicit format string. The date, datetime, and time types support this method.
Follow-up: How can formatted text be parsed back? Use the corresponding strptime behavior with a format that describes the input representation.
datetime.datedatetime.timedatetime.datetimedatetime.timedeltadatetime.tzinfodatetime.timezonedatetime.strftimedatetime.strptime