Python:将秒转换为hh:mm:ss [英] Python: convert seconds to hh:mm:ss
问题描述
请,如何将int(数字1秒)转换为这些格式: mm:ss 或 hh:mm:ss ?
Please, how to convert an int (number a seconds) to these formats: mm:ss or hh:mm:ss ?
我需要使用Python代码(如果可能,在Django模板中)这样做。
I need to do this with Python code (and if possible in a Django template ?).
非常感谢! / p>
Thank you very much ;-)
推荐答案
我不能相信任何许多答案都给出了我认为一个明显的做法我甚至不是荷兰人! - ) - 高达24小时的秒数(86399秒,具体来说):
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'
在Django模板中更加精细化,因为 time
过滤器支持一个时髦的时间格式语法(启发,我相信,从PHP),还需要datetime模块和时区实现(如pytz)来准备数据。例如:
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:
>>> 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.
这篇关于Python:将秒转换为hh:mm:ss的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!