Confusing datetime.datetime

Hans Mulder hansmu at xs4all.nl
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 = 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???

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, x1.day))

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, x1.day, 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