This question already has an answer here:
这个问题已经有了答案:
- How to convert seconds to hours, minutes and seconds? 7 answers
- 如何将秒转换成小时、分钟和秒?7的答案
Please, how to convert an int (number a seconds) to these formats: mm:ss or hh:mm:ss ?
请问如何将int(数字a秒)转换成这些格式:mm:ss还是hh:mm:ss ?
I need to do this with Python code (and if possible in a Django template ?).
我需要使用Python代码(如果可能的话,使用Django模板?)
Thank you very much ;-)
非常感谢;-)
10 个解决方案
#1
91
I can't believe any of the many answers gives what I'd consider the "one obvious way to do it" (and I'm not even Dutch...!-) -- up to just below 24 hours' worth of seconds (86399 seconds, specifically):
我不敢相信这些答案中的任何一个给出了我所认为的“一种显而易见的方法”(我甚至都不是荷兰人…!)
>>> import time
>>> time.strftime('%H:%M:%S', time.gmtime(12345))
'03:25:45'
Doing it in a Django template's more finicky, since the time
filter supports a funky time-formatting syntax (inspired, I believe, from PHP), and also needs the datetime module, and a timezone implementation such as pytz, to prep the data. For example:
使用Django模板更挑剔,因为时间过滤器支持一种奇怪的时间格式语法(我相信,这是受到PHP启发的),而且还需要datetime模块和一个时区实现(如pytz)来准备数据。例如:
>>> from django import template as tt
>>> import pytz
>>> import datetime
>>> tt.Template('{{ x|time:"H:i:s" }}').render(
... tt.Context({'x': datetime.datetime.fromtimestamp(12345, pytz.utc)}))
u'03:25:45'
Depending on your exact needs, it might be more convenient to define a custom filter for this formatting task in your app.
根据您的确切需要,在应用程序中定义这个格式化任务的自定义过滤器可能更方便。
#2
53
>>> a = datetime.timedelta(seconds=65)
datetime.timedelta(0, 65)
>>> str(a)
'0:01:05'
#3
17
Code that does what was requested, with examples, and showing how cases he didn't specify are handled:
执行所要求的代码,并举例说明如何处理未指定的案例:
def format_seconds_to_hhmmss(seconds):
hours = seconds // (60*60)
seconds %= (60*60)
minutes = seconds // 60
seconds %= 60
return "%02i:%02i:%02i" % (hours, minutes, seconds)
def format_seconds_to_mmss(seconds):
minutes = seconds // 60
seconds %= 60
return "%02i:%02i" % (minutes, seconds)
minutes = 60
hours = 60*60
assert format_seconds_to_mmss(7*minutes + 30) == "07:30"
assert format_seconds_to_mmss(15*minutes + 30) == "15:30"
assert format_seconds_to_mmss(1000*minutes + 30) == "1000:30"
assert format_seconds_to_hhmmss(2*hours + 15*minutes + 30) == "02:15:30"
assert format_seconds_to_hhmmss(11*hours + 15*minutes + 30) == "11:15:30"
assert format_seconds_to_hhmmss(99*hours + 15*minutes + 30) == "99:15:30"
assert format_seconds_to_hhmmss(500*hours + 15*minutes + 30) == "500:15:30"
You can--and probably should--store this as a timedelta rather than an int, but that's a separate issue and timedelta doesn't actually make this particular task any easier.
您可以——也可能应该——将它存储为一个timedelta而不是int,但这是一个单独的问题,而timedelta实际上并没有使这个特定的任务变得更容易。
#4
8
Have you read up on the datetime module?
你读过datetime模块吗?
Edit/update: SilentGhost's answer has the details my answer leaves out. If you like this answer, +1 his as well (or instead). Reposted here:
编辑/更新:SilentGhost的答案包含了我的答案遗漏的细节。如果你喜欢这个答案,+1他也一样(或者相反)。转发:
>>> a = datetime.timedelta(seconds=65)
datetime.timedelta(0, 65)
>>> str(a)
'0:01:05'
#5
7
You can calculate the number of minutes and hours from the number of seconds by simple division:
你可以用简单的除法计算秒数和分钟数:
seconds = 12345
minutes = seconds // 60
hours = minutes // 60
print "%02d:%02d:%02d" % (hours, minutes % 60, seconds % 60)
print "%02d:%02d" % (minutes, seconds % 60)
Here //
is pythons integer division.
这里//是python的整数除法。
#6
7
If you use divmod, you are immune to different flavors of integer division:
如果你使用divmod,你就不会受到整数除法的影响:
# show time strings for 3800 seconds
# easy way to get mm:ss
print "%02d:%02d" % divmod(3800, 60)
# easy way to get hh:mm:ss
print "%02d:%02d:%02d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(3800,),60,60])
# function to convert floating point number of seconds to
# hh:mm:ss.sss
def secondsToStr(t):
return "%02d:%02d:%02d.%03d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(t*1000,),1000,60,60])
print secondsToStr(3800.123)
Prints:
打印:
63:20
01:03:20
01:03:20.123
#7
1
Just be careful when dividing by 60: division between integers returns an integer -> 12/60 = 0 unless you import division from future. The following is copy and pasted from Python 2.6.2:
在除以60的时候要小心:整数之间的除法会返回整数-> 12/60 = 0,除非你从未来导入除法。以下是Python 2.6.2的拷贝和粘贴:
IDLE 2.6.2
>>> 12/60
0
>>> from __future__ import division
>>> 12/60
0.20000000000000001
#8
0
Not being a python person but easiest without any libraries just:
不是一个python的人,但是没有任何库是最简单的:
total = 3800
seconds = total % 60
total = total - seconds
hours = total / 3600
total = total - (hours * 3600)
mins = total / 60
Updated code, thanks sth
更新的代码,谢谢…
#9
0
Besides the fact that Python has built in support for dates and times (see bigmattyh's response), finding minutes or hours from seconds is easy:
除了Python已经构建了对日期和时间的支持(参见bigmattyh的响应)之外,从秒中找出分钟或小时是很容易的:
minutes = seconds / 60
hours = minutes / 60
Now, when you want to display minutes or seconds, MOD them by 60 so that they will not be larger than 59
现在,当你想要显示分钟或秒时,对它们进行60的修改,这样它们就不会大于59
#10
0
If you need to do this a lot, you can precalculate all possible strings for number of seconds in a day:
如果你需要做很多,你可以预先计算所有可能的字符串,一天几秒:
try:
from itertools import product
except ImportError:
def product(*seqs):
if len(seqs) == 2:
for s1 in seqs[0]:
for s2 in seqs[1]:
yield (s1,s2)
else:
for s in seqs[0]:
for p in product(*seqs[1:]):
yield (s,) + p
hhmmss = {}
i = 0
for (h,m,s) in product(range(24),range(60),range(60)):
hhmmss[i] = "%02d:%02d:%02d" % (h,m,s)
i += 1
Now conversion of seconds to format string is a fast dict lookup:
现在将秒转换为格式字符串是一个快速的命令查找:
print hhmmss[12345]
prints
打印
'03:25:45'
#1
91
I can't believe any of the many answers gives what I'd consider the "one obvious way to do it" (and I'm not even Dutch...!-) -- up to just below 24 hours' worth of seconds (86399 seconds, specifically):
我不敢相信这些答案中的任何一个给出了我所认为的“一种显而易见的方法”(我甚至都不是荷兰人…!)
>>> import time
>>> time.strftime('%H:%M:%S', time.gmtime(12345))
'03:25:45'
Doing it in a Django template's more finicky, since the time
filter supports a funky time-formatting syntax (inspired, I believe, from PHP), and also needs the datetime module, and a timezone implementation such as pytz, to prep the data. For example:
使用Django模板更挑剔,因为时间过滤器支持一种奇怪的时间格式语法(我相信,这是受到PHP启发的),而且还需要datetime模块和一个时区实现(如pytz)来准备数据。例如:
>>> from django import template as tt
>>> import pytz
>>> import datetime
>>> tt.Template('{{ x|time:"H:i:s" }}').render(
... tt.Context({'x': datetime.datetime.fromtimestamp(12345, pytz.utc)}))
u'03:25:45'
Depending on your exact needs, it might be more convenient to define a custom filter for this formatting task in your app.
根据您的确切需要,在应用程序中定义这个格式化任务的自定义过滤器可能更方便。
#2
53
>>> a = datetime.timedelta(seconds=65)
datetime.timedelta(0, 65)
>>> str(a)
'0:01:05'
#3
17
Code that does what was requested, with examples, and showing how cases he didn't specify are handled:
执行所要求的代码,并举例说明如何处理未指定的案例:
def format_seconds_to_hhmmss(seconds):
hours = seconds // (60*60)
seconds %= (60*60)
minutes = seconds // 60
seconds %= 60
return "%02i:%02i:%02i" % (hours, minutes, seconds)
def format_seconds_to_mmss(seconds):
minutes = seconds // 60
seconds %= 60
return "%02i:%02i" % (minutes, seconds)
minutes = 60
hours = 60*60
assert format_seconds_to_mmss(7*minutes + 30) == "07:30"
assert format_seconds_to_mmss(15*minutes + 30) == "15:30"
assert format_seconds_to_mmss(1000*minutes + 30) == "1000:30"
assert format_seconds_to_hhmmss(2*hours + 15*minutes + 30) == "02:15:30"
assert format_seconds_to_hhmmss(11*hours + 15*minutes + 30) == "11:15:30"
assert format_seconds_to_hhmmss(99*hours + 15*minutes + 30) == "99:15:30"
assert format_seconds_to_hhmmss(500*hours + 15*minutes + 30) == "500:15:30"
You can--and probably should--store this as a timedelta rather than an int, but that's a separate issue and timedelta doesn't actually make this particular task any easier.
您可以——也可能应该——将它存储为一个timedelta而不是int,但这是一个单独的问题,而timedelta实际上并没有使这个特定的任务变得更容易。
#4
8
Have you read up on the datetime module?
你读过datetime模块吗?
Edit/update: SilentGhost's answer has the details my answer leaves out. If you like this answer, +1 his as well (or instead). Reposted here:
编辑/更新:SilentGhost的答案包含了我的答案遗漏的细节。如果你喜欢这个答案,+1他也一样(或者相反)。转发:
>>> a = datetime.timedelta(seconds=65)
datetime.timedelta(0, 65)
>>> str(a)
'0:01:05'
#5
7
You can calculate the number of minutes and hours from the number of seconds by simple division:
你可以用简单的除法计算秒数和分钟数:
seconds = 12345
minutes = seconds // 60
hours = minutes // 60
print "%02d:%02d:%02d" % (hours, minutes % 60, seconds % 60)
print "%02d:%02d" % (minutes, seconds % 60)
Here //
is pythons integer division.
这里//是python的整数除法。
#6
7
If you use divmod, you are immune to different flavors of integer division:
如果你使用divmod,你就不会受到整数除法的影响:
# show time strings for 3800 seconds
# easy way to get mm:ss
print "%02d:%02d" % divmod(3800, 60)
# easy way to get hh:mm:ss
print "%02d:%02d:%02d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(3800,),60,60])
# function to convert floating point number of seconds to
# hh:mm:ss.sss
def secondsToStr(t):
return "%02d:%02d:%02d.%03d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(t*1000,),1000,60,60])
print secondsToStr(3800.123)
Prints:
打印:
63:20
01:03:20
01:03:20.123
#7
1
Just be careful when dividing by 60: division between integers returns an integer -> 12/60 = 0 unless you import division from future. The following is copy and pasted from Python 2.6.2:
在除以60的时候要小心:整数之间的除法会返回整数-> 12/60 = 0,除非你从未来导入除法。以下是Python 2.6.2的拷贝和粘贴:
IDLE 2.6.2
>>> 12/60
0
>>> from __future__ import division
>>> 12/60
0.20000000000000001
#8
0
Not being a python person but easiest without any libraries just:
不是一个python的人,但是没有任何库是最简单的:
total = 3800
seconds = total % 60
total = total - seconds
hours = total / 3600
total = total - (hours * 3600)
mins = total / 60
Updated code, thanks sth
更新的代码,谢谢…
#9
0
Besides the fact that Python has built in support for dates and times (see bigmattyh's response), finding minutes or hours from seconds is easy:
除了Python已经构建了对日期和时间的支持(参见bigmattyh的响应)之外,从秒中找出分钟或小时是很容易的:
minutes = seconds / 60
hours = minutes / 60
Now, when you want to display minutes or seconds, MOD them by 60 so that they will not be larger than 59
现在,当你想要显示分钟或秒时,对它们进行60的修改,这样它们就不会大于59
#10
0
If you need to do this a lot, you can precalculate all possible strings for number of seconds in a day:
如果你需要做很多,你可以预先计算所有可能的字符串,一天几秒:
try:
from itertools import product
except ImportError:
def product(*seqs):
if len(seqs) == 2:
for s1 in seqs[0]:
for s2 in seqs[1]:
yield (s1,s2)
else:
for s in seqs[0]:
for p in product(*seqs[1:]):
yield (s,) + p
hhmmss = {}
i = 0
for (h,m,s) in product(range(24),range(60),range(60)):
hhmmss[i] = "%02d:%02d:%02d" % (h,m,s)
i += 1
Now conversion of seconds to format string is a fast dict lookup:
现在将秒转换为格式字符串是一个快速的命令查找:
print hhmmss[12345]
prints
打印
'03:25:45'