Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Fixed UTC offsets and datetime formatting with `strftime` and `isoformat`

Attach a fixed UTC offset without changing the wall clock reading, then render the same datetime as both a custom string and an ISO 8601 string.

Version: Python 3.12

Syntax

dt.replace(tzinfo=tz) -> datetime
dt.astimezone(tz) -> datetime
dt.strftime(format) -> str
dt.isoformat(sep='T', timespec='auto') -> str

In Python 3.12, dt.replace(tzinfo=tz) returns a new datetime.datetime with tzinfo set and the date and clock fields unchanged. Use it when you know the recorded wall time belongs to that offset. timezone(timedelta(...)) represents a fixed offset from UTC, not a zone with daylight saving rules.

Attaching an offset is not conversion. For an aware datetime, dt.astimezone(tz) keeps the same instant and adjusts the date and clock fields as needed for the target zone. Replacing tzinfo with a different offset keeps the clock reading but changes the instant it represents.

dt.strftime(format) returns a string that follows your pattern. In the example, %d/%m/%Y %H:%M:%S %z puts the day before the month, leaves out fractional seconds, and writes the offset as +0530. On a naive object, %z produces an empty string. Support for some directives varies by platform, and month names depend on the locale.

dt.isoformat() returns the date and time as a string and appends the offset if utcoffset() is not None. sep is the single character between the date and time, defaulting to 'T'. The result is not always ISO 8601 compliant: sep can be a character the standard does not allow, and even with the default separator, the UTC offset can contain seconds or fractional seconds, which ISO 8601 does not allow in offsets. The default timespec='auto' includes seconds and adds six fractional digits only when microseconds are nonzero. A shorter setting such as timespec='milliseconds' truncates rather than rounds; an invalid timespec raises ValueError. Neither formatting method modifies the object.

Examples

from datetime import datetime, timedelta, timezone

wall_time = datetime(2025, 3, 29, 14, 5, 6, 987654)
fixed_offset = timezone(timedelta(hours=5, minutes=30))
annotated = wall_time.replace(tzinfo=fixed_offset)

print(annotated.strftime('%d/%m/%Y %H:%M:%S %z'))
print(annotated.isoformat(timespec='milliseconds'))

Result

29/03/2025 14:05:06 +0530
2025-03-29T14:05:06.987+05:30

The clock still reads `14:05:06` after attaching `+05:30`. The first line is the custom format with `+0530`; the second is the ISO format with `+05:30` and the fraction `.987`.

Related lessons

  • Python · Lesson 31 · Intermediate · Version: 3

Sources