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

编程入门 行业动态 更新时间:2024-10-23 17:35:06
本文介绍了在 Python 中将秒转换为 hh:mm:ss的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何将 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

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

发布评论

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

>www.elefans.com

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