将标准的24小时格式转换为99 python的范围

时间:2018-04-18 16:14:31

标签: python

任务是将输入在几秒钟内转换为人类可读的时间,格式为HH:MM:SS。

<body>

<label>
    <span>Office Location</span><br>
    <select name="office" id="office" onChange="loadDoc()">
        <option value="">Select Office Location</option>
        <option value="place1">Place 1</option>
        <option value="place2">Place 2</option>
        <option value="place3">Place 3</option>
        <option value="place4">Place 4</option>
    </select>
</label>
<div id="drawing"></div>
<script>
    function loadDoc(){
        var xhttp = new XMLHttpRequest();
        var office = document.getElementsByName("office");
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200){
                document.getElementById("drawing").innerHTML = this.responseText;
            }
        };
        xhttp.open("GET", "fetch_details.php?=q" +office, true);
        xhttp.send();
    }
</script>

到目前为止,这就是我所拥有的,并且有效。

唯一的问题是小时应显示在00 - 99范围内,目前是24小时。

e.g。如果输入为359999秒,则应输出99:59:59。这也是顺便说一句的最长时间。

错误:

'00:00:00'应该等于'24:00:00'

'03:59:59'应该等于'99:59:59'

'20:36:54'应该等于'44:36:54'

问题:如何将小时数设为99格式?

2 个答案:

答案 0 :(得分:0)

我认为你可以推出自己的秒解析器。例如:

def make_readable(seconds):
    if seconds > 359999:
        raise ValueError('Invalid number of seconds: {}'.format(seconds))

    s = seconds % 60
    seconds //= 60

    m = seconds % 60
    seconds //= 60

    h = seconds

    return '{:02d}:{:02d}:{:02d}'.format(h, m, s)

print(make_readable(359999)) # Prints 99:59:59
print(make_readable(65)) # Prints 00:01:05

答案 1 :(得分:0)

以下是使用divmod代替time模块的解决方案。

def make_readable(seconds):
    hours, rem = divmod(seconds, 3600)
    minutes, seconds = divmod(rem, 60)

    # The following makes sure a one-digit time quantity is written as 0X
    return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)

以下是输出示例。

make_readable(359999) # '99:59:59'
make_readable(3661)  # '01:01:01'

# This will continue working over 35,999 seconds
make_readable(360000) # '100:00:00'