Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert seconds to readable format time

Tags:

python

time

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
like image 561
user3590149 Avatar asked Jan 09 '23 16:01

user3590149


1 Answers

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
like image 172
Burhan Khalid Avatar answered Jan 17 '23 19:01

Burhan Khalid