如何获取小时:分钟

9 投票
4 回答
26457 浏览
提问于 2025-04-15 16:18

我这里有一个脚本(不是我写的),它用来计算我卫星接收器中电影的时长。它显示的格式是分钟:秒

我想把它改成小时:分钟

我需要做哪些修改呢?

以下是相关的脚本部分:

if len > 0:
    len = "%d:%02d" % (len / 60, len % 60)
else:
    len = ""

res = [ None ]

我已经通过用3600来除得到了小时,但就是无法得到分钟...

提前谢谢你们

彼得

4 个回答

1

所以,len是电影的秒数吗?这个名字起得不好。Python已经把len这个词用在别的地方了。换个名字吧。

def display_movie_length(seconds):
    # the // ensures you are using integer division
    # You can also use / in python 2.x
    hours = seconds // 3600   

    # You need to understand how the modulo operator works
    rest_of_seconds = seconds % 3600  

    # I'm sure you can figure out what to do with all those leftover seconds
    minutes = minutes_from_seconds(rest_of_seconds)

    return "%d:%02d" % (hours, minutes)

你只需要弄清楚minutes\_from\_seconds()应该是什么样子的。如果你还是不明白,可以查一下“取模运算符”是什么。

13
hours = secs / 3600
minutes = secs / 60 - hours * 60

len = "%d:%02d" % (hours, minutes)
hours = secs // 3600
minutes = secs // 60 - hours * 60

len = "%d:%02d" % (hours, minutes)

或者,对于更新版本的Python:

20

你可以使用timedelta

from datetime import timedelta
str(timedelta(minutes=100))[:-3]
# "1:40"

撰写回答