A little help with time calculations

Steve Holden steve at holdenweb.com
Tue Oct 18 14:01:21 EDT 2005


iminal wrote:
> I am trying to make a very simple program and am very new to the whole
> programming thing. my program is supposed to ask a user for any time in
> the for format XX:XX:XX and then ask for a time corrrection to add or
> subtract to this. my only problem is that once the user inputs the time
> and the correction its adding it like it was 100 not to 60 any help?
> 
If you're new to programming you may not yet have realised that many 
problems come down to finding appropriate representations for things.

Since you want to do arithmetic on times, why not store them as seconds? 
Then you just need to work out how to convert times to seconds, and 
seconds to times - Python's arithmetic will do the rest.

See if you can make anything of these functions (which I haven't tested, 
so you're allowed to complain if they don't work ;-):

def timetosecs(s):
     hms = s.split(":")     # [hh, mm, ss]
     secs = 0
     for t in hms:
         secs = secs * 60 + int(t)
     return secs

def secstotime(secs):
     hms = []
     while secs:
         hms.append(str(secs % 60))
         secs = secs // 60
     return ":".join(hms)

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list