time.strftime in 2.4.1 claims data out of range when not

Raymond Hettinger vze4rx4y at verizon.net
Fri Apr 22 06:16:47 EDT 2005


[Sheila King]
> I have a web app that has been running just fine for several months under
> Python 2.2.2.
>
> We are preparing to upgrade the server to run Python 2.4.1.
>
> However, part of my web app is throwing an error on this code (that has
> previously worked without exception):
>
> >>> time.strftime("%Y-%m-%d", (Y, M, D, 0,0,0,0,0,0))
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: day of year out of range
> >>> Y
> 2005
> >>> M
> 5
> >>> D
> 15L

>From the docs for time.strptime:
    "The default values used to fill in any missing data are (1900, 1, 1, 0, 0,
0, 0, 1, -1) ".

So, you could change the offending code line to:
>>> strftime("%Y-%m-%d", (Y, M, D, 0, 0, 0, 0, 1, -1) )
'2005-05-15'

Since the rules for handling missing, inconsistent, or out-of-range tuple fields
are not defined, even that revision has some risk.  To future-proof the code,
use strptime() to generate a well-formed time tuple:

>>> strptime('%d-%d-%d' % (y,m,d), '%Y-%m-%d')
(2005, 5, 15, 0, 0, 0, 6, 135, -1)
>>> strftime("%Y-%m-%d", _)
'2005-05-15'

This somewhat circular technique sticks with the documented API but allows you
to access all of the time module's options (like accessing the locale's names
for days of the week and months of the year).


Raymond Hettinger










More information about the Python-list mailing list