Python time mktime() 方法



Python time mktime() 方法將本地時間的物件形式轉換為秒。此方法是 localtime() 的逆函式,並接受 struct_time 物件或完整的 9 元組作為其引數。為了與 time() 保持相容性,它返回一個浮點數。

如果輸入值不能表示為有效時間,則會引發 OverflowErrorValueError

語法

以下是 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

示例

現在讓我們嘗試將一個 "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

示例

如果我們根據 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)

示例

如果作為引數傳遞的值不是有效的時間元件,則該方法會引發 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

示例

如果作為引數傳遞的值超過了元組元件的限制,則該方法會引發 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:\Tutorialspoint\Programs\Python Time Programs\mktimedemo.py", line 4, in 
    secs = time.mktime(t)
TypeError: mktime(): illegal time tuple argument
python_date_time.htm
廣告