在Python中将秒转换为hh:mm:ss

编程入门 行业动态 更新时间:2024-10-23 19:18:23
本文介绍了在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

本文发布于:2023-10-16 12:11:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497513.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   Python   ss   mm

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!