datetime and daylight savings problem

wittempj@hotmail.com martin.witte at gmail.com
Tue Oct 11 16:43:08 EDT 2005


When working with timezones datetime objects are represented in the
tzinfo object you supply, eg. when you define these classes (and run
them on a system set to  Paris time):

from datetime import tzinfo, timedelta, datetime
import time

class UTC(tzinfo):
    """UTC timezone"""
    def utcoffset(self, dt):
        return timedelta(0)

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return timedelta(0)

class CET(tzinfo):
    """CET timezone"""
    def utcoffset(self, dt):
        return timedelta(seconds = -time.timezone)
    def dst(self, dt):
        return timedelta(0)
    def tzname(self, dt):
        return "CET"


class CEST(tzinfo):
    """CET timezone with DST"""
    def utcoffset(self, dt):
        return timedelta(seconds = -time.altzone)
    def dst(self, dt):
        return timedelta(seconds = -time.altzone) - \
                timedelta(seconds = -time.timezone)
    def tzname(self, dt):
        return "CEST"

And you create these objects:

utc = UTC()
cet = CET()
cest = CEST()
d = datetime(2005,06,01,16,59,tzinfo=utc)

This statement
print 'UTC %s' % d
Will print:
UTC 2005-06-01 16:59:00+00:00

And this one:
print 'As CET %s' % d.astimezone(cet)
Will print:
As CET 2005-06-01 17:59:00+01:00

And this one:
print 'As CET with DST %s' % d.astimezone(cest)
Will print:
As CET with DST 2005-06-01 18:59:00+02:00

Additional:
This:
d = datetime(2005,06,01,16,59,tzinfo=cet)
print cet, d

Will print:
<__main__.CET object at 0xb7d3aaac> 2005-06-01 16:59:00+01:00

And this:
d = datetime(2005,06,01,16,59,tzinfo=cest)
print cest, d
Will print:
<__main__.CEST object at 0xb7d3aaec> 2005-06-01 16:59:00+02:00

So at least with these tzinfo objects everything is as expected, I'm
not sure where your actual problem is, is it in the pytz module (with
which I do not have experience)?




More information about the Python-list mailing list