mktime()函数将本地时间元组转换为Unix时间戳,需传入包含9个元素的元组或struct_time对象,自动按系统时区调整,常用于时间存储与计算,注意输入应为本地时间而非UTC以避免错误。

Python 中 mktime() 函数用于将本地时间的 struct_time 对象或包含 9 个元素的元组转换为 **Unix 时间戳**(即从 1970 年 1 月 1 日 00:00:00 UTC 到指定时间的秒数)。它属于 time 模块,是时间处理中常用的方法之一。
mktime() 接收一个表示本地时间的元组或 struct_time 对象,格式如下:
其中前 6 项是关键,后三项可由系统推算,但传入时需完整。
示例:
将 2024 年 4 月 5 日 10:30:00 转为时间戳:
<pre class="brush:php;toolbar:false;">import time <h1>构造本地时间元组</h1><p>local_time_tuple = (2024, 4, 5, 10, 30, 0, 4, 96, -1)</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><p>timestamp = time.mktime(local_time_tuple) print(timestamp) # 输出类似 1712303400.0</p>
mktime() 假设输入的时间是本地时间,并根据系统的时区和夏令时规则自动调整。例如在中国(CST, UTC+8),同样的时间比 UTC 快 8 小时,所以计算出的时间戳会对应到 UTC 的更早时刻。
对比 calendar.timegm():它用于 UTC 时间元组转时间戳,不考虑本地时区。
对比示例:
<pre class="brush:php;toolbar:false;">import time
import calendar
<p>local_tuple = (2024, 4, 5, 10, 30, 0, 4, 96, -1)</p><h1>本地时间转时间戳(考虑时区)</h1><p>local_ts = time.mktime(local_tuple)</p><h1>UTC 时间转时间戳(不考虑时区)</h1><p>utc_ts = calendar.timegm(local_tuple)</p><p>print("本地 mktime:", local_ts)
print("UTC timegm:", utc_ts)</p>基本上就这些。mktime() 是把结构化本地时间变成时间戳的直接方式,理解它的时区假设是正确使用的关键。
以上就是python mktime()如何计算时间的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号