问题描述
如何将 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 等实现,用于准备数据.例如:
根据您的具体需求,在您的应用中为此格式化任务定义自定义过滤器可能更方便.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!