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

前端 未结 12 2098
执笔经年
执笔经年 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:37

    Using datetime:

    With the ':0>8' format:

    from datetime import timedelta
    
    "{:0>8}".format(str(timedelta(seconds=66)))
    # Result: '00:01:06'
    
    "{:0>8}".format(str(timedelta(seconds=666777)))
    # Result: '7 days, 17:12:57'
    
    "{:0>8}".format(str(timedelta(seconds=60*60*49+109)))
    # Result: '2 days, 1:01:49'
    

    Without the ':0>8' format:

    "{}".format(str(timedelta(seconds=66)))
    # Result: '00:01:06'
    
    "{}".format(str(timedelta(seconds=666777)))
    # Result: '7 days, 17:12:57'
    
    "{}".format(str(timedelta(seconds=60*60*49+109)))
    # Result: '2 days, 1:01:49'
    

    Using time:

    from time import gmtime
    from time import strftime
    
    # NOTE: The following resets if it goes over 23:59:59!
    
    strftime("%H:%M:%S", gmtime(125))
    # Result: '00:02:05'
    
    strftime("%H:%M:%S", gmtime(60*60*24-1))
    # Result: '23:59:59'
    
    strftime("%H:%M:%S", gmtime(60*60*24))
    # Result: '00:00:00'
    
    strftime("%H:%M:%S", gmtime(666777))
    # Result: '17:12:57'
    # Wrong
    

提交回复
热议问题