Confusing datetime.datetime

Hans Mulder hansmu at
Fri Jul 6 18:41:58 CEST 2012

On 6/07/12 00:55:48, Damjan wrote:
> On 05.07.2012 16:10, Damjan wrote:
>> I've been struggling with an app that uses
>> Postgresql/Psycopg2/SQLAlchemy  and I've come to this confusing
>> behaviour of datetime.datetime.
> Also this:
> #! /usr/bin/python2
> # retardations in python's datetime
> import pytz
> TZ = pytz.timezone('Europe/Skopje')
> from datetime import datetime
> x1 =
> x2 = datetime(x1.year, x1.month,, tzinfo=TZ)
> assert x1.tzinfo == x2.tzinfo
> WHY does the assert throw an error???

Because x1 and x2 have different time zones.

The tzinfo field in x2 is equal to TZ and has a UTC offset of 1 hour.
The tzinfo field in x1 contains the DST version of that timezone,
with a UTC offset of 2 hours, because Skopje is currently on DST.

I think you want:

x2 = TZ.localize(datetime(x1.year, x1.month,

That produces a datetime with the year, month and day set as indicated
and tzinfo set to the correct UTC offset for that date, at 00:00 hours.

Or maybe you need:

x2 = TZ.localize(datetime(x1.year, x1.month,, 12))
x2 = x2.replace(hour=0)

That determines whether DST should be on at noon, and then resets the
hour field to zero.  This produces the same outcome as the one liner,
except on days when DST is switched on or off.

Hope this helps,

-- HansM

More information about the Python-list mailing list