incrementing a time tuple by one day

Bengt Richter bokr at oz.net
Thu Sep 23 15:04:22 EDT 2004


On Thu, 23 Sep 2004 16:22:08 +0000, "David Stockwell" <winexpert at hotmail.com> 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'
                      ^^^^
the trouble is that you are adding a time delta in seconds since some epoch
instead of adding 24*60*60 seconds (one day).

Note your supposed 1-day delta value in seconds:
 >>> time.mktime((0,0,1,0,0,0,0,0,0))
 944035200.0

Or in days:
 >>> time.mktime((0,0,1,0,0,0,0,0,0))/(60*60*24)
 10926.333333333334


 >>> import time
 >>> 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))
 >>> z = time.mktime(x) + 24*60*60
 >>> print time.ctime(y)
 Thu Jan 27 08:00:00 2022
 >>> print time.ctime(z)
 Sat Feb 29 00:00:00 1992
 >>> print time.ctime(time.mktime(x))
 Fri Feb 28 00:00:00 1992

To get a one-day delta, you could calculate it (in general you'd have to
watch out for leap stuff, but this case seems to work)

 >>> time.mktime((0,0,1,0,0,0,0,0,0)) - time.mktime((0,0,0,0,0,0,0,0,0))
 86400.0
 >>> oneday = time.mktime((0,0,1,0,0,0,0,0,0)) - time.mktime((0,0,0,0,0,0,0,0,0))
 >>> time.ctime(time.mktime(x)+oneday)
 'Sat Feb 29 00:00:00 1992'

>
>It appears to have decremented by a day and a month instead of increment.
You didn't read the entire date ;-)
>
>What am I doing wrong?
Misinterpreting time.mktime((0,0,0,0,0,0,0,0,0)) as being zero-based?

 >>> time.mktime((0,0,0,0,0,0,0,0,0))
 943948800.0

Regards,
Bengt Richter



More information about the Python-list mailing list