incrementing a time tuple by one day

Donn Cave donn at u.washington.edu
Thu Sep 23 15:06:31 EDT 2004


In article <QcudnRWf360rm87cRVn-vg at powergate.ca>,
 Peter Hansen <peter at engcorp.com> wrote:
> David Stockwell wrote:
> > I'm sure this has been asked before, but I wasn't able to find it.
> > 
> > First off I know u can't change a tuple but if I wanted to increment a 
> > time tuple by one day what is the standard method to do that?
> > 
> > I've tried the obvious things and haven't gotten very far.
> > 
> > I have a time tuple that was created like this:
> > aDate = '19920228'
> > x = time.strptime(aDate,"%Y%m%d")
> > print x
> > (1992, 2, 28, 0, 0, 0, 4, 59, -1)
> > 
> > y = time.mktime(x) + time.mktime((0,0,1,0,0,0,0,0,0))
> > print y
> > 1643277600.0
> > print time.ctime(y)
> > 'Thu Jan 27 05:00:00 2022'
> > 
> > It appears to have decremented by a day and a month instead of increment.
> > 
> > What am I doing wrong?
> 
> What you're doing wrong is: not using the datetime module...
> 
>  >>> aDate = '19920228'
>  >>> x = time.strptime(aDate, '%Y%m%d')
>  >>> print x
> (1992, 2, 28, 0, 0, 0, 4, 59, -1)
>  >>> d = datetime.datetime.fromtimestamp(time.mktime(x))
>  >>> d
> datetime.datetime(1992, 2, 28, 0, 0)
>  >>> y = d + datetime.timedelta(days=1)
>  >>> y.ctime()
> 'Sat Feb 29 00:00:00 1992'


$ python
Python 2.2 (#1, 11/12/02, 23:31:59) 
[GCC Apple cpp-precomp 6.14] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ImportError: No module named datetime
>>> 

Well, who knows, maybe datetime is the answer for him,
but if not, I would just use 24*60*60 instead of trying
to get one day in seconds out of mktime().  (I think if
you look at the date closer, it isn't decremented all!)

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list