CKTIS / Python
strftime: format a datetime with a UTC offset
Attach a known fixed UTC offset without changing the clock time, then display the same datetime using a custom format and an ISO 8601 representation.
Version: Python 3.12
Syntax
dt.strftime(format) -> str
dt.replace(tzinfo=offset) -> datetime
dt.isoformat(sep='T', timespec='auto') -> strIn Python 3.12, strftime(format) is an instance method of datetime.datetime. It returns a str based on your format string without changing the object. In the example, %d/%m/%Y gives day, month, and year, and %H:%M:%S gives the 24-hour clock hour, minute, and second. The slashes, colons, and spaces are literal characters.
When you know the clock reading belongs to a fixed UTC offset, use replace(tzinfo=offset) with a timezone built from a timedelta. This returns a new aware datetime with the same date and clock fields. It attaches an offset rather than converting the time, and a fixed offset does not track daylight saving changes. Use astimezone() on an already aware datetime to express the same instant in another time zone.
%z writes the UTC offset: +05:30 becomes +0530, and a naive datetime produces an empty string for this directive. %Z writes the time zone name returned by tzname() instead of the numeric offset. If tzname() returns None, as it does when tzinfo is None, %Z produces an empty string. The full set of supported directives varies by platform, and textual month and weekday names can depend on the locale.
Use strftime when you control the layout and isoformat() when you want an ISO 8601 representation. Both return text without changing the datetime. By default, isoformat() separates the date and time with T and writes this example's offset as +05:30.
Examples
from datetime import datetime, timedelta, timezone
wall_time = datetime(2024, 6, 15, 9, 5, 7)
offset = timezone(timedelta(hours=5, minutes=30))
aware = wall_time.replace(tzinfo=offset)
print(aware.strftime("%d/%m/%Y %H:%M:%S %z"))
print(aware.isoformat())Result
15/06/2024 09:05:07 +0530 2024-06-15T09:05:07+05:30
Both lines retain `09:05:07`: the first uses the `strftime` pattern and ends in `+0530`; the second uses `isoformat()` and ends in `+05:30`.
Related lessons
- Python · Lesson 31 · Intermediate · Version: 3