Showing posts with label datetime. Show all posts
Showing posts with label datetime. Show all posts


Python tip - converting HH:MM:SS time into more understandable format

The Torque resource manager for clusters prints out amounts of time -- CPU time, or walltime -- in HH:MM:SS format. For small numbers, it's easy enough to understand: 04:00:00 = 4 hours. But for larger numbers, I wanted the time amount specified in days, hours, minutes, and seconds. Here's a quick way to do it using the datetime module. (I'm working with Python 2.6 here, which is what comes with RHEL6.) It uses a list comprehension to split up the HH:MM:SS time string. (BTW, I am using ipython as the interactive Python shell.)

In [4]: import re, datetime

In [5]: def timedeltastr(timestr):
   ...:     dayspat = re.compile(r'\ days?,')
   ...:     t = [int(i) for i in timestr.split(':')]
   ...:     td = datetime.timedelta(hours=t[0], minutes=t[1], seconds=t[2])
   ...:     return dayspat.sub('d', str(td))
In [6]: timestr = '3400:00:00'

In [7]: timedeltastr(timestr)
Out[7]: '141d 16:00:00'