Python time mktime() 方法将本地时间的对象形式转换为秒。此方法是 localtime() 的逆函数,并接受 struct_time 对象或完整的 9 元组作为其参数。它返回一个浮点数,以便与 time() 兼容。
如果输入值不能表示为有效时间,则会引发 OverflowError 或 ValueError。
语法
以下是 Python mktime() 方法的语法 -
time.mktime(t)
参数
- t − 这是 struct_time 元组或完整的 9 元组。
返回值
此方法返回一个浮点数,以便与 time() 兼容。
例以下示例显示了 Python time mktime() 方法的用法。在这里,我们将一个普通的 9 元组作为参数传递给这个方法。
import time
t = (2009, 2, 17, 17, 3, 38, 1, 48, 0)
secs = time.mktime(t)
print("Time in seconds:", secs)
print("Time represented as a string:", time.asctime(time.localtime(secs)))
当我们运行上述程序时,它会产生以下结果——
Time in seconds: 1234870418.0
Time represented as a string: Tue Feb 17 17:03:38 2009
Time represented as a string: Tue Feb 17 17:03:38 2009
例
现在让我们尝试将对象 “struct_time” 作为参数传递给此方法。
我们使用 time.struct_time() 方法将 9 元组转换为对象 “time_struct”。然后,此对象将作为参数传递给 mktime() 方法,使用该方法我们检索以秒为单位的本地时间。
import time
t = (2009, 2, 17, 17, 3, 38, 1, 48, 0)
time_struct = time.struct_time(t)
secs = time.mktime(time_struct)
print("Time in seconds:", secs)
print("Time represented as a string:", time.asctime(time.localtime(secs)))
如果我们编译并运行上面的程序,输出显示如下 -
Time in seconds: 1234870418.0
Time represented as a string: Tue Feb 17 17:03:38 2009
Time represented as a string: Tue Feb 17 17:03:38 2009
例
如果我们根据 UTC 时间传递参数,该方法会提供错误的时间戳作为返回值。
从 gmtime() 方法以对象形式获取的当前时间将作为参数传递给 mktime() 方法。然后,作为 mktime() 方法的返回值获取的浮点值将作为参数传递给 gmtime() 方法。gmtime() 方法的两个返回值不同。
import time
t = time.gmtime()
print("Time as object:", t)
secs = time.mktime(t)
print("Time in seconds:", secs)
obj = time.gmtime(secs)
print("Time as object:", obj)
上述程序的输出显示如下 -
Time as object: time.struct_time(tm_year=2023, tm_mon=1, tm_mday=10, tm_hour=6, tm_min=31, tm_sec=33, tm_wday=1, tm_yday=10, tm_isdst=0)
Time in seconds: 1673312493.0
Time as object: time.struct_time(tm_year=2023, tm_mon=1, tm_mday=10, tm_hour=1, tm_min=1, tm_sec=33, tm_wday=1, tm_yday=10, tm_isdst=0)
Time in seconds: 1673312493.0
Time as object: time.struct_time(tm_year=2023, tm_mon=1, tm_mday=10, tm_hour=1, tm_min=1, tm_sec=33, tm_wday=1, tm_yday=10, tm_isdst=0)
例
如果作为参数传递的值不是有效的时间组件,则该方法将引发 OverflowError。
import time
t = (202, 1, 10, 12, 6, 55, 1, 10, 0)
secs = time.mktime(t)
print("Time in seconds:", secs)
上述程序的输出如下 -
Traceback (most recent call last):
File "d:\Alekhya\Programs\Python Time Programs\mktimedemo.py", line 4, in
secs = time.mktime(t)
OverflowError: mktime argument out of range
File "d:\Alekhya\Programs\Python Time Programs\mktimedemo.py", line 4, in
secs = time.mktime(t)
OverflowError: mktime argument out of range
例
如果作为参数传递的值超过元组组件的限制,该方法将引发 TypeError。
import time
t = (2023, 1, 10, 12, 6, 55, 1, 10, 0, 44)
secs = time.mktime(t)
print("Time in seconds:", secs)
在执行上述程序时,结果如下所示 -
Traceback (most recent call last):
File "d:\qikepu\Programs\Python Time Programs\mktimedemo.py", line 4, in
secs = time.mktime(t)
TypeError: mktime(): illegal time tuple argument
File "d:\qikepu\Programs\Python Time Programs\mktimedemo.py", line 4, in
secs = time.mktime(t)
TypeError: mktime(): illegal time tuple argument