How to convert a UTC datetime to a local datetime using only standard library?

datetime, python, python-datetime, timezone

Solution

I think I figured it out: computes number of seconds since epoch, then converts to a local timzeone using time.localtime, and then converts the time struct back into a datetime...

EPOCH_DATETIME = datetime.datetime(1970,1,1)
SECONDS_PER_DAY = 24*60*60

def utc_to_local_datetime( utc_datetime ):
    delta = utc_datetime - EPOCH_DATETIME
    utc_epoch = SECONDS_PER_DAY * delta.days + delta.seconds
    time_struct = time.localtime( utc_epoch )
    dt_args = time_struct[:6] + (delta.microseconds,)
    return datetime.datetime( *dt_args )

It applies the summer/winter DST correctly:

>>> utc_to_local_datetime( datetime.datetime(2010, 6, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 6, 6, 19, 29, 7, 730000)
>>> utc_to_local_datetime( datetime.datetime(2010, 12, 6, 17, 29, 7, 730000) )
datetime.datetime(2010, 12, 6, 18, 29, 7, 730000)

Problem

I have a python `datetime` instance that was created using `datetime.utcnow()` and persisted in database. For display, I would like to convert the `datetime` instance retrieved from the database to local `datetime` using the default local timezone (i.e., as if the `datetime` was created using `datetime.now()`). How can I convert the UTC `datetime` to a local `datetime` using only python standard library (e.g., no `pytz` dependency)? It seems one solution would be to use `datetime.astimezone(tz)`, but how would you get the default local timezone?

Original source

Related problems