I have variable that has seconds and I want to convert to detailed time format. I have like this at the moment.
runTime = '%s Hours:Minutes:Seconds' % time.strftime("%H:%M:%S", time.gmtime(runTime))
Outputs:
17:25:46 Hours:Minutes:Seconds
I would like to have it formated as such:
17 Hours 25 Minutes 46 Seconds
Ultimately I would like to be able shorten for smaller values:
So if the value is minutes and seconds it would like like
15 Minutes 5 Seconds
and if has more then 24 hours then days
1 Days 15 Hours 5 Minutes 1 Seconds
You should use the excellent dateutil
package and then your task becomes trivial:
>>> from dateutil.relativedelta import relativedelta as rd
>>> fmt = '{0.days} days {0.hours} hours {0.minutes} minutes {0.seconds} seconds'
>>> print(fmt.format(rd(seconds=62745)))
0 days 17 hours 25 minutes 45 seconds
A bit of an advanced example, which only shows values for those fields that are non-zero:
>>> intervals = ['days','hours','minutes','seconds']
>>> x = rd(seconds=12345)
>>> print(' '.join('{} {}'.format(getattr(x,k),k) for k in intervals if getattr(x,k)))
3 hours 25 minutes 45 seconds
>>> x = rd(seconds=1234432)
>>> print(' '.join('{} {}'.format(getattr(x,k),k) for k in intervals if getattr(x,k)))
14 days 6 hours 53 minutes 52 seconds
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With