Timezone and ISO8601 struggles with datetime and xml.utils.iso8601.parse

Samuel knipknap at gmail.com
Fri Sep 9 20:23:09 CEST 2005

> Take a look at the utcoffset method of datetime objects.

This returns 0.
However, meanwhile I figured out a way to do this:

Every datetime object by default does not handle timezones at all, and
as such "isoformat" does not return an offset in the ISO8601 string.
The only way around this appears to be passing the tzinfo to the
constructor every time (datetime.tzinfo is not writeable). I am not
aware of a python-provided implementation for a conrete tzinfo, so I
copied this code:

from datetime import *
import time as _time

STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
    DSTOFFSET = timedelta(seconds = -_time.altzone)


class LocalTimezone(tzinfo):
    def utcoffset(self, dt):
        if self._isdst(dt):
            return DSTOFFSET
            return STDOFFSET

    def dst(self, dt):
        if self._isdst(dt):
            return DSTDIFF
            return ZERO

    def tzname(self, dt):
        return _time.tzname[self._isdst(dt)]

    def _isdst(self, dt):
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, -1)
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
        return tt.tm_isdst > 0

from the Python documentation into my program. (I am sure there must be
a better way to do this though.) Then, when passing the
tz.LocalTimezone instance to datetime, isoformat() returns the string
with an offset appended (e.g. +02:00).
The resulting string can then also successfully be parsed with

Thanks for your help!


More information about the Python-list mailing list