CKTIS / Python
Attach a UTC offset with datetime.replace()
Attach a known fixed UTC offset without changing the calendar date or clock reading, then format the result as either a custom string or an ISO 8601 string.
Version: Python 3.12
Syntax
dt.replace(year=dt.year, month=dt.month, day=dt.day, hour=dt.hour, minute=dt.minute, second=dt.second, microsecond=dt.microsecond, tzinfo=dt.tzinfo, fold=dt.fold)
aware = dt.replace(tzinfo=timezone(timedelta(hours=2)))
aware.strftime("%d/%m/%Y %H:%M:%S %z")
aware.isoformat()In Python 3.12, datetime.datetime.replace is an instance method of the datetime class in the datetime module. It returns a new object with the supplied fields replaced and the omitted fields copied from the original. This is not time arithmetic: for example, hour=24 raises ValueError instead of rolling over to the next day.
If you know the recorded clock reading belongs to +02:00, create tz = timezone(timedelta(hours=2)) and call dt.replace(tzinfo=tz). A naive datetime becomes aware, but the date and clock reading stay the same. A fixed offset does not account for daylight saving changes. dt.replace(tzinfo=None) removes the time zone information without converting the date or time.
To express the same instant in another zone, call astimezone(tz) on an aware datetime: it may adjust the clock reading or date, but it preserves the instant. On a naive datetime, astimezone() assumes the system's local zone. The separate fold argument is keyword-only; in a repeated local interval, 0 selects the earlier instant and 1 the later one. Omitting fold preserves its original value.
strftime() follows an explicit format string; %z produces +0200 here. The full set of supported directives varies by platform. With no arguments, isoformat() returns an ISO 8601 string with a T separator and the offset +02:00. Neither formatter changes the object or converts the time.
Examples
from datetime import datetime, timedelta, timezone
wall_time = datetime(2024, 6, 15, 9, 30)
fixed_offset = timezone(timedelta(hours=2))
aware = wall_time.replace(tzinfo=fixed_offset)
print(aware.strftime("%d/%m/%Y %H:%M:%S %z"))
print(aware.isoformat())Result
15/06/2024 09:30:00 +0200 2024-06-15T09:30:00+02:00
Both lines retain `09:30:00`. The custom format puts the day before the month and writes the offset as `+0200`; the ISO 8601 format writes `+02:00`.
Related lessons
- Python · Lesson 31 · Intermediate · Version: 3
Sources
- Python 3.12 datetime documentation: datetime.replace()
- Python 3.12 datetime documentation: datetime.astimezone()
- Python 3.12 datetime documentation: timezone
- Python 3.12 datetime documentation: datetime.strftime()
- Python 3.12 datetime documentation: strftime() and strptime() Behavior
- Python 3.12 datetime documentation: datetime.isoformat()
- PEP 495 – Local Time Disambiguation