[New-bugs-announce] [issue28602] `tzinfo.fromutc()` fails when used for a fold-aware tzinfo implementation

Paul G report at bugs.python.org
Thu Nov 3 14:55:50 EDT 2016


New submission from Paul G:

After PEP-495, the default value for non-fold-aware datetimes is that they return the DST side, not the STD side (as was the assumption before PEP-495). This invalidates an assumption made in `tz.fromutc()`. See lines 991-1000 of datetime.py:

    dtdst = dt.dst()
    if dtdst is None:
        raise ValueError("fromutc() requires a non-None dst() result")
    delta = dtoff - dtdst
    if delta:
        dt += delta
        dtdst = dt.dst()
        if dtdst is None:
            raise ValueError("fromutc(): dt.dst gave inconsistent "
                             "results; cannot convert")

Line 997 (https://github.com/python/cpython/blob/be8de928e5d2f1cd4d4c9c3e6545b170f2b02f1b/Lib/datetime.py#L997) assumes that an ambiguous datetime will return the STD side, not the DST side, and as a result, if you feed it a date in UTC that should resolve to the STD side, it will actually return 1 hour (or whatever the DST offset is) AFTER the ambiguous date that should be returned.

If 997 is changed to:

    dtdst = dt.replace(fold=1).dst()

That will not affect fold-naive zones (which are instructed to ignore the `fold` parameter) and restore the original behavior. This will allow fold-aware timezones to be implemented as a wrapper around `fromutc()` rather than a complete re-implementation, e.g.:

class FoldAwareTzInfo(datetime.tzinfo):
    def fromutc(self, dt):
        dt_wall = super(FoldAwareTzInfo, self).fromutc(dt)

        is_fold = self._get_fold_status(dt, dt_wall)

        return dt_wall.replace(fold=is_fold)

----------
messages: 280007
nosy: belopolsky, p-ganssle, tim.peters
priority: normal
severity: normal
status: open
title: `tzinfo.fromutc()` fails when used for a fold-aware tzinfo implementation
type: behavior
versions: Python 3.6, Python 3.7

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue28602>
_______________________________________


More information about the New-bugs-announce mailing list