datetime1 - datetime0, same tzinfo, different dst

Stéphane Bidoul stephane.bidoul at softwareag.com
Sun Jul 27 10:35:29 EDT 2003


Hi,

I'm playing around with the new datetime module.
Looks nice, and a welcome addition to the core...

I've a question about a behaviour of
substractions of "aware" datetimes around DST switch.

The problem is that the difference gives wrong results
when the 2 datetimes have the same tzinfo instance,
but have different utc offsets due to DST.
The behaviour is consistent with what the documentation
says, but I find it quite unintuitive.

Is that the designed behaviour?

Assuming doctzinfo is the sample tzinfo module form the documentation,
below is a commented session that illustrates question.
My win2k sp4 system is in Belgium: GMT+1 with DST.

Thanks.

-sbi

Python 2.3c1 (#44, Jul 18 2003, 14:32:36) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> from doctzinfo import utc, Local, LocalTimezone

Let's create 2 dates, d0: winter time
and d1: summer time.

>>> d0 = datetime(2003,3,30,tzinfo=Local) 
>>> print d0.dst()
0:00:00 # ok: this is winter time

>>> d1 = datetime(2003,3,31,tzinfo=Local)
>>> print d1.dst()
1:00:00 # ok, this is summer time, DST is 1 hour

>>> print d1.astimezone(utc) - d0.astimezone(utc)
23:00:00 # difference of UTC is 23h, ok, it's a short day...

>>> print d1 - d0
1 day, 0:00:00 # now that's surprising!!!

Well, it's actually consistent with the documentation 
that says that no utc conversion is done when the 2 dates
have the same tzinfo, but I find it somewhat unintuitive
in this case.

Now, let's do the same with 2 different tzinfo
instances, that have the same behaviour has the
Local instance.

>>> d0 = datetime(2003,3,30,tzinfo=LocalTimezone())
>>> print d0.dst()
0:00:00
>>> d1 = datetime(2003,3,31,tzinfo=LocalTimezone())
>>> print d1.dst()
1:00:00
>>> print d1.astimezone(utc) - d0.astimezone(utc)
23:00:00 # as expected
>>> print d1 - d0
23:00:00 # as expected too

So in this case it works, but should we create
new tzinfo instances for each datetime we create.
The sample tzinfo module seems to imply they
are best used as singletons.




More information about the Python-list mailing list