modifying a time.struct_time

Chris Angelico rosuav at gmail.com
Sat Dec 24 02:13:13 EST 2011


On Sat, Dec 24, 2011 at 5:04 PM, Jason Friedman <jason at powerpull.net> wrote:
> Not particularly elegant, but I believe accurate and relying only on
> the stated struct_time contract:

Funny! But a binary search would be better, I think.


t = time.time()
time1 = time.localtime(t)
print("Local time is {}.".format(time1))
est1 = t + 365*86400
est2 = est1 + 86400 # Assume that the year is between 365 and 366 days
long (widen this if assumption not valid)
while True:
   est = (est1 + est2) / 2
   time2 = time.localtime(t)
   cmp = is_local_time_different_by_one_year(time1, time2):
   if cmp<0: est1 = est
   elif cmp>0: est2 = est
   else:
       print("One year later is {}".format(time2))
       break

Could do with a few more improvements. Also, it requires that the
comparison function return -1, 0, or 1, in the same way that strcmp()
does (not a difficult enhancement, but I'm off to Christmas dinner
with the family so I'll leave it as an exercise for the reader).

ChrisA



More information about the Python-list mailing list