在Python中将秒转换为hh:mm:ss [英] Convert seconds to hh:mm:ss in Python

查看:225
本文介绍了在Python中将秒转换为hh:mm:ss的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将整数(秒)转换为 mm:ss hh:mm:ss 的格式?

How do I convert an int (number of seconds) to the formats mm:ss or hh:mm:ss?

我需要使用Python代码(如果可能的话,在Django模板中)执行此操作。

I need to do this with Python code (and if possible in a Django template).

推荐答案

I无法相信众多答案中的任何一个都能给出我认为的一种明显的实现方式(而且我什至都不是荷兰人!!-)-长达不到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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆