Python time time() 方法



Python 的 time() 方法返回當前的 UTC 時間。此返回值以自紀元以來的秒數表示,並作為浮點數獲得。

此方法不接受任何引數,因此始終返回當前的 UTC 時間。

注意 - 即使時間始終以浮點數返回,但並非所有系統都提供比 1 秒更高的精度的時間。雖然此函式通常返回非遞減值,但如果在兩次呼叫之間系統時鐘已回撥,則它可能會返回低於先前呼叫的值。為了避免這種精度損失,可以使用 time_ns() 方法。

語法

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

time.time()

引數

此方法不接受任何引數。

返回值

此方法返回 UTC 中的當前時間。

示例

以下示例演示了 time() 方法的使用。

import time

t = time.time()
print("Current UTC Time in seconds:", t)

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

Current UTC Time in seconds: 1673432458.9977512

示例

從 time() 方法獲得的返回值可以透過將其作為引數傳遞給 gmtime() 或 strftime() 等方法來格式化。

在以下示例中,我們使用 time() 方法獲取了以秒為單位的當前時間。這些秒作為引數傳遞給 gmtime() 方法,以使用 struct_time 物件的各個欄位來表示它,以指示時間的元素。但是,作為額外的步驟,我們還可以嘗試透過將其作為引數傳遞給 strftime() 方法來簡化此物件的結構。

import time

t = time.time()
print("Current UTC Time in seconds:", t)

#Formatting the seconds obtained from time() using gmtime()
fmt = time.gmtime(t)
print("Current Formatted UTC Time:", fmt)

#Formatting the object obtained from gmtime() using strftime()
strf = time.strftime("%D %T", fmt)
print("Current Formatted UTC Time:",strf)

Current UTC Time in seconds: 1673435474.7526345
Current Formatted UTC Time: time.struct_time(tm_year=2023, tm_mon=1, tm_mday=11, tm_hour=11, tm_min=11, tm_sec=14, tm_wday=2, tm_yday=11, tm_isdst=0)
Current Formatted UTC Time: 01/11/23 11:12:11

示例

不僅可以獲取UTC時間,我們還可以透過將此方法的返回值作為引數傳遞給localtime()方法來計算本地時間。

我們討論過time()方法處理的是UTC時間,並返回自紀元以來的秒數(以UTC時間計算)。但是,如果從時區的角度考慮,表示這些秒數的浮點數在UTC時間中將等於本地時間中的秒數。因此,我們也可以透過傳遞time()方法的返回值,使用localtime()方法格式化當前的本地時間。

import time

t = time.time()
print("Current UTC Time in seconds:", t)

#Formatting the seconds obtained using localtime()
fmt = time.localtime(t)
print("Current Formatted Local Time:", fmt)

#Formatting the seconds obtained using strftime()
strf = time.strftime("%D %T", fmt)
print("Current Formatted Local Time:",strf)

如果我們編譯並執行上面的程式,輸出將顯示如下:

Current UTC Time in seconds: 1673438690.5065289
Current Formatted Local Time: time.struct_time(tm_year=2023, tm_mon=1, tm_mday=11, tm_hour=17, tm_min=34, tm_sec=50, tm_wday=2, tm_yday=11, tm_isdst=0)
Current Formatted Local Time: 01/11/23 17:34:50
python_date_time.htm
廣告