Python time localtime() 方法



Python time localtime() 方法將 Python 時間轉換為本地時間。Python 時間是指系統紀元以來經過的秒數;而本地時間是相對於系統地理位置的時間。本地時間也由一個物件表示。

此方法類似於 localtime() 方法,並接受浮點數作為其可選引數。如果未提供或為 None,則使用 time() 方法返回的當前時間。但是,與 localtime() 方法不同的是,當對給定時間應用夏令時時,物件中的 dst 標誌設定為 1。

語法

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

time.localtime([ sec ])

引數

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

返回值

此方法返回系統紀元以來經過的時間,表示為一個物件。

示例

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

import time

lt = time.localtime()
print("Current local time:", lt)

執行上述程式時,將產生以下結果:

Current local 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 秒後的日期。此程式執行的系統的紀元為本地時間的“Thu Jan 1 05:30:00 1970”。此方法返回經過秒數後的時間。

import time

# Passing the seconds elapsed as an argument to this method
lt = time.localtime(1000)
print("Python local time:", lt)

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

示例

localtime() 方法也可用於獲取系統紀元(本地時間)。

據說該方法返回給定經過秒數後的本地時間,該時間基於系統的紀元計算得出。因此,如果我們將引數作為“0”傳遞,則該方法將返回系統的紀元。

import time

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

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

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

示例

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

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

import time

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

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

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