如何将 int(秒数)转换为 mm:ss 或 hh:mm:ss 格式?
我需要用 Python 代码来做这件事(如果可能的话,在 Django 模板中).
解决方案我不敢相信众多答案中的任何一个给出了我认为一种明显的方法"(我什至不是荷兰人...!-) -- 最多低于 24 小时的秒数(具体来说是 86399 秒):
>>>导入时间>>>time.strftime('%H:%M:%S', time.gmtime(12345))'03:25:45'在 Django 模板中做这件事比较挑剔,因为 time 过滤器支持时髦的时间格式语法(我相信是从 PHP 中获得灵感的),并且还需要 datetime 模块和时区pytz 等实现,用于准备数据.例如:
>>>从 django 导入模板为 tt>>>进口pytz>>>导入日期时间>>>tt.Template('{{ x|time:"H:i:s" }}').render(... tt.Context({'x': datetime.datetime.fromtimestamp(12345, pytz.utc)}))你'03:25:45'根据您的具体需求,在您的应用中为此格式化任务定义自定义过滤器可能更方便.
How do I convert an int (number of seconds) to the formats mm:ss or hh:mm:ss?
I need to do this with Python code (and if possible in a Django template).
解决方案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:
>>> 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
发布评论