A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://mail.python.org/pipermail/python-list/2005-September/301381.html below:

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

Timezone and ISO8601 struggles with datetime and xml.utils.iso8601.parseSamuel knipknap at gmail.com
Fri Sep 9 14:23:09 EDT 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)
else:
    DSTOFFSET = STDOFFSET

DSTDIFF = DSTOFFSET - STDOFFSET

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

    def dst(self, dt):
        if self._isdst(dt):
            return DSTDIFF
        else:
            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
xml.utils.iso8601.parse().

Thanks for your help!

-Samuel


More information about the Python-list mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4