How to convert a timedelta object to a string?

Carl J. Van Arsdall cvanarsdall at mvista.com
Thu Sep 14 16:53:44 EDT 2006


Basically I used the datetime module and timedelta objects to calculate 
a difference between two times.  Now I'm trying to figure out how I make 
that time delta a string HH:MM:SS to show elapsed time.  I've spent tons 
of time looking at the module's documentation but I'm not seeing how 
those methods will help me.  Can anyone help me with this? 

Here's what I'm trying to do, assum that resultsDict is a dictionary of 
objects that have various pieces of information including a start time 
and a stop time that are strings which I extracted from a file in an 
earlier part of the program.  I use regEx to split up the hours, 
minutes, and seconds and create timedelta objects, which I then subtract 
to get the different.  What I need is to get the value in duration as 
HH:MM:SS as a string:


#There's lots of other code above this, but I just need help with this part
  timeRegex = re.compile(r'(\d\d):(\d\d):(\d\d)')
  for key in resultsDict.keys():
    if resultsDict[key].stop != None:
      parsedTime = timeRegex.match(resultsDict[key].start)
      startDelta = datetime.timedelta(seconds=int(parsedTime.group(3)), 
minutes=int(parsedTime.group(2)), hours=int(parsedTime.group(1)))
      parsedTime = timeRegex.match(resultsDict[key].stop)
      stopDelta = datetime.timedelta(seconds=int(parsedTime.group(3)), 
minutes=int(parsedTime.group(2)), hours=int(parsedTime.group(1)))
      duration = stopDelta - startDelta






Thanks,

-carl


-- 

Carl J. Van Arsdall
cvanarsdall at mvista.com
Build and Release
MontaVista Software




More information about the Python-list mailing list