[Zope3-dev] timetuple and utctimetuple

Guido van Rossum guido@python.org
Tue, 19 Nov 2002 11:41:49 -0500


> Today I was playing with the datetime module again, and I noticed a bug:
> 
>   date(2001, 1, 3).strftime('%Y-%m-%d') == "2001-01-02"

Yes, this is a bug.

> if you happen to live west from UTC.  The bug happens because strftime
> passes a time_t timestamp (which is always in UTC) to localtime, and
> localtime adds your timezone offset before conversion to a tuple.  The
> fix is to use gmtime, which returns the same date you manually
> constructed.  I've just commited this fix to datetime in Zope3 CVS.

Please don't just change the datetime.py that's in Zope3.  It's a copy
of the datetime.py in the "nondist" part of the Python CVS tree, and
the latter is the master copy:

http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/nondist/sandbox/datetime/

If you have a bug or patch to report, please submit a SourceForge bug
report for the latter and assign it to me, Fred Drake or Tim Peters.

> Grepping around for other uses of time.localtime I noticed one in
> date.timetuple().  Assuming that this is the same bug, and that you
> always want the following equality to hold
> 
>   date(y, m, d).timetuple()[:3] == (y, m, d)

Yes.

> I applied and commited the same fix (only I accidantally pasted the unit
> test to TestDateTime instead of TestDate, will fix that later).
> 
> Then I noticed utctimetuple() and began to have doubts.  Maybe I
> shouldn't have "fixed" timetuple()?  What should be the exact semantics
> of those methods?  Assume the following code:
> 
>   tt1 = dt.timetuple()
>   tt2 = dt.utctimetuple()
> 
> Without my "fix" the following holds:
> 
>   tt1 is a time tuple in local time when dt is in UTC
>   tt1 is not meaningful when dt is in local time

This is clearly bogus.

>   tt2 is a time tuple in UTC when dt is in UTC
>   tt2 is a time tuple in local time when dt is in localtime
> 
> Personally, I find it a bit confusing.  I think that dt.timetuple()
> should return a broken-down time representation in the same timezone dt
> was defined in.

Yes.

> With my "fix"
> 
>   tt1 is a time tuple in local time when dt is in local time
>   tt1 is a time tuple in UTC when dt is in UTC
> 
> but then timetuple() and utctimetuple() are identical.  Do we want
> 
>   tt2 is a time tuple in UTC when dt is in localtime
>   tt2 is not meaningful when dt is in UTC
> 
> ?  In that case utctimetuple should be modified.

I think that only datetimetz should have an utctimetuple() method.

> BTW the date class claims to have a utctimetuple() in its docstring,
> but utctimetuple is only defined in datetime.

I'll fix this (in my copy).

> P.S. Would you like me to commit my prototype datetime.time
> implementation to Zope3 CVS after we finish it?

I'd rather that you submitted a context diff for Python's datetime.py
to the SF patch tracker.

--Guido van Rossum (home page: http://www.python.org/~guido/)