How do I convert seconds to hours, minutes and seconds?

前端 未结 12 2291
执笔经年
执笔经年 2020-11-22 11:00

I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds.

Is there an easy way to convert the seconds to

12条回答
  •  深忆病人
    2020-11-22 11:34

    hours (h) calculated by floor division (by //) of seconds by 3600 (60 min/hr * 60 sec/min)

    minutes (m) calculated by floor division of remaining seconds (remainder from hour calculation, by %) by 60 (60 sec/min)

    similarly, seconds (s) by remainder of hour and minutes calculation.

    Rest is just string formatting!

    def hms(seconds):
        h = seconds // 3600
        m = seconds % 3600 // 60
        s = seconds % 3600 % 60
        return '{:02d}:{:02d}:{:02d}'.format(h, m, s)
    
    print(hms(7500))  # Should print 02h05m00s
    

提交回复
热议问题