Issue 8026: strftime bug when timedelta is negative (original) (raw)
Ubuntu,8.10, python 2.5.1, intel-32 OSX, 10.6.2, python 2.5.4, intel-32 strftime() when used with timedelta(days=-ve) has problems with year rollover. Test script demonstrates the problem, call as: python ./test_strftime.py --startdate=01-02-2010 --count=-32
print of the datetime object gives correct years: 2009-12-31 00:00:00 2010-01-01 00:00:00 2010-01-02 00:00:00 2010-01-03 00:00:00 2010-01-04 00:00:00 2010-01-05 00:00:00
print of the strftime generated string goes wrong for first few days in Jan: 01/Feb/2010|31/Dec/2009|01/Jan/2009|02/Jan/2009|03/Jan/2009|04/Jan/2010
This happens using year 2010, 2011, 2012.
Is Ok when using 2009.
goes wrong differently when using 2008 but not 2007. Goes wrong differently for 2006.
This is not a bug. The issue boils down to the following:
from datetime import * d = datetime(2010, 1, 1) d, d.strftime("%G") (datetime.datetime(2010, 1, 1, 0, 0), '2009')
and OP expects '2010' instead. Python behavior is correct as can be verified using GNU date utility:
$ date --date=20100101 +%G 2009
The confusion comes from the fact that %G is formatted as the ISO 8601 year. This year is the one that contains the greater part of the week (Monday as the first day of the week).
Here is another illustration:
d = date(2009,12,31) for i in range(7): ... (d+timedelta(i)).strftime("%F %a %G %V") ... '2009-12-31 Thu 2009 53' '2010-01-01 Fri 2009 53' '2010-01-02 Sat 2009 53' '2010-01-03 Sun 2009 53' '2010-01-04 Mon 2010 01' '2010-01-05 Tue 2010 01' '2010-01-06 Wed 2010 01'
Note that week 1 of 2010 started on Monday, 2010-01-04.
OP is advised to change %G to %Y in his code.