Datetime transforms

A more interactive version of the graph on page 32 of What you need to know about datetimes.

From \ To POSIX struct_time (UTC) Naïve datetime (local) Naïve datetime (UTC) Aware datetime
POSIX identity(t) time.gmtime(t) datetime.fromtimestamp(t, None) datetime.utcfromtimestamp(t) datetime.fromtimestamp(t, tz)
struct_time (UTC) calendar.timegm(struct_time) identity(struct_time) datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None) datetime.datetime(struct_time[:6]) datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)
Naïve datetime (local) calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple()) stz.localize(dt, is_dst=None).utctimetuple() identity(dt) stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None) stz.localize(dt, is_dst=None)
Naïve datetime (UTC) calendar.timegm(dt.utctimetuple()) dt.utctimetuple() dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None) identity(dt) dt.replace(tzinfo=UTC)
Aware datetime calendar.timegm(dt.utctimetuple()) dt.utctimetuple() dt.astimezone(tz).replace(tzinfo=None) dt.astimezone(UTC).replace(tzinfo=None) dt.astimezone(tz)
From / To POSIX struct_time (UTC) Naïve datetime (local) Naïve datetime (UTC) Aware datetime
t
source POSIX timestamp
struct_time
source "time tuple" instance
dt
source datetime instance
stz
source pytz.timezone() instance (for naïve local datetimes)
tz
destination pytz.timezone() instance
UTC
pytz.UTC
identity
lambda x: x