Python time gmtime() 方法



Python 的 gmtime() 方法用於獲取自紀元以來經過的時間,以物件的形式表示。該物件使用關鍵字“struct_time”表示,幷包含各種欄位以指定時間元素。此方法接受一個浮點數作為引數,該浮點數表示經過的秒數,並以物件的形式提供 UTC 時間。

與 ctime() 方法不同,此方法返回 UTC 時間的物件表示形式。

注意:如果未傳遞引數或作為 None 傳遞,則預設情況下,該方法使用 time() 返回的值作為其引數。struct_time 物件的 dst_flag 欄位將始終為 0。

語法

以下是 Python time gmtime() 方法的語法:-

time.gmtime([ sec ])

引數

  • sec - (可選)表示經過秒數的浮點數。

返回值

此方法將系統中自紀元以來經過的時間作為物件返回。

示例

以下示例顯示了 Python time gmtime() 方法的使用。我們沒有向此方法的可選引數傳遞任何值。因此,該方法預設情況下將 time() 方法的返回值作為其引數。該方法返回當前時間作為物件。

import time

gt = time.gmtime()
print("Current UTC time:", gt)

當我們執行上述程式時,它會產生以下結果:-

Current UTC time: time.struct_time(tm_year=2023, tm_mon=1, tm_mday=9, tm_hour=12, tm_min=28, tm_sec=40, tm_wday=0, tm_yday=9, tm_isdst=0)

示例

如果傳遞的引數是表示自系統紀元以來經過的秒數的整數,則該方法將返回經過時間後的日期的物件表示形式。

在下面的示例中,我們試圖找到自紀元以來 1000 秒後的日期。執行此程式的系統的紀元在 UTC 時間為“Thu Jan 1 00:00:00 1970”。此方法返回經過秒數後的時間。

import time

# Passing the seconds elapsed as an argument to this method
gt = time.gmtime(1000)
print("Python UTC time:", gt)

Python UTC time: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=16, tm_sec=40, tm_wday=3, tm_yday=1, tm_isdst=0)

示例

gmtime() 方法也可用於獲取系統在 UTC 時間中的紀元。

據說該方法返回根據系統紀元計算的給定經過秒數後的時間。因此,如果我們將引數作為“0”傳遞,則該方法將返回系統的紀元。如果需要查詢紀元的本地時間,則使用 ctime() 方法。

import time

# Passing the seconds elapsed as an argument to this method
gt = time.gmtime(0)
print("The epoch of the system:", gt)

讓我們編譯並執行上述程式,以產生以下結果:-

The epoch of the system: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

示例

此方法不考慮表示經過秒數的浮點數引數的小數部分。

讓我們將 2.99 秒作為引數傳遞給 gmtime() 方法。即使該數字幾乎等於 3 秒,也預計該方法將完全忽略小數部分,並將引數僅視為 2 秒。它在下面的示例中顯示。

import time

# Passing the seconds elapsed as an argument to this method
gt = time.gmtime(2.99)
print("Time after elapsed seconds:", gt)

如果我們編譯並執行上述程式,則輸出如下:-

Time after elapsed seconds: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=2, tm_wday=3, tm_yday=1, tm_isdst=0)
python_date_time.htm
廣告