python 如何获得小时:分钟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1784952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How get hours:minutes
提问by Peter
I have a script here (not my own) which calculates the length of a movie in my satreceiver. It displays the length in minutes:seconds
我这里有一个脚本(不是我自己的),它在我的卫星接收器中计算电影的长度。它以分钟:秒显示长度
I want to have that in hours:minutes
我想在几小时:分钟内完成
What changes do I have to make?
我必须做出哪些改变?
This is the peace of script concerned:
这是有关脚本的和平:
if len > 0:
len = "%d:%02d" % (len / 60, len % 60)
else:
len = ""
res = [ None ]
I already got the hours by dividing by 3600 instead of 60 but can't get the minutes...
我已经通过除以 3600 而不是 60 得到了小时数,但无法得到分钟数...
Thanks in advance
提前致谢
Peter
彼得
回答by Marc Belmont
You can use timedelta
您可以使用 timedelta
from datetime import timedelta
str(timedelta(minutes=100))[:-3]
# "1:40"
回答by wallyk
hours = secs / 3600
minutes = secs / 60 - hours * 60
len = "%d:%02d" % (hours, minutes)
Or, for more recent versions of Python:
或者,对于更新版本的 Python:
hours = secs // 3600
minutes = secs // 60 - hours * 60
len = "%d:%02d" % (hours, minutes)
回答by jcdyer
So len the number of seconds in the movie? That's a bad name. Python already uses the word len for something else. Change it.
那么电影中的秒数是多少?那是个坏名字。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)
All you need to do is figure out what minutes\_from\_seconds()
is supposed to look like. If you're still confused, do a little research on the modulo operator.
您需要做的就是弄清楚minutes\_from\_seconds()
应该是什么样子。如果您仍然感到困惑,请对模运算符进行一些研究。
回答by Anentropic
There is a nice answer to this here https://stackoverflow.com/a/20291909/202168(a later duplicate of this question)
这里有一个很好的答案https://stackoverflow.com/a/20291909/202168(此问题的后续副本)
However if you are dealing with timezone offsets in a datetime string then you need to also handle negative hours, in which case the zero padding in Martijn's answer does not work
但是,如果您正在处理日期时间字符串中的时区偏移,那么您还需要处理负小时数,在这种情况下,Martijn 的答案中的零填充不起作用
eg it would return -4:00
instead of -04:00
例如它会返回-4:00
而不是-04:00
To fix this the code becomes slightly longer, as below:
为了解决这个问题,代码会稍微长一些,如下所示:
offset_h, offset_m = divmod(offset_minutes, 60)
sign = '-' if offset_h < 0 else '+'
offset_str = '{}{:02d}{:02d}'.format(sign, abs(offset_h), offset_m)