Confusing datetime.datetime

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jul 6 03:28:56 CEST 2012


On Fri, 06 Jul 2012 00:55:48 +0200, Damjan wrote:

> Also this:
> 
> #! /usr/bin/python2
> # retardations in python's datetime
> 
> import pytz
> TZ = pytz.timezone('Europe/Skopje')
>
> from datetime import datetime
> 
> x1 = datetime.now(tz=TZ)
> x2 = datetime(x1.year, x1.month, x1.day, tzinfo=TZ)
> 
> assert x1.tzinfo == x2.tzinfo
> 
> 
> WHY does the assert throw an error???

I don't have pytz, so I can't test your exact code. But using my own time 
zone class, it seems to work fine in Python 2.5, 2.6 and 2.7:

from datetime import datetime, timedelta, tzinfo
ZERO = timedelta(0)
HOUR = timedelta(hours=1)

class UTC(tzinfo):
    def utcoffset(self, dt):
        return ZERO
    def tzname(self, dt):
        return "UTC"
    def dst(self, dt):
        return ZERO

utc = UTC()
t1 = datetime.now(tz=utc)
t2 = datetime(t1.year, t1.month, t1.day, tzinfo=utc)
assert t1.tzinfo == t2.tzinfo


No assertion error at all.

This makes me think that the "retardation" as you put it is not in 
Python's datetime module at all, but in pytz.

What does TZ == TZ give? If it returns False, I recommend you report it 
as a bug against the pytz module.


-- 
Steven



More information about the Python-list mailing list