Python time asctime() 方法



在討論 Python time asctime() 方法的工作原理之前,讓我們瞭解一下時間的不同表示方式。

在 Python time 模組中,時間可以用兩種簡單的方式表示:元組或物件。元組更抽象;它按順序儲存日期和時間,元組的每個元素代表時間的特定元素。例如,(2023, 1, 9, 10, 51, 77, 0, 9, 0) 表示時間“Mon Jan 9 10:51:77 2023”。但是,僅憑觀察元組無法辨別哪個元素代表什麼。這就是引入物件的原因,以便更清楚地理解這些元素。

物件,通常表示為 struct_time,定義了各種欄位來儲存時間的各種元素。因此,訪問它們就更容易了。例如,一個物件將時間表示為 (tm_year=2023, tm_mon=1, tm_mday=9, tm_hour=10, tm_min=51, tm_sec=77, tm_wday=0, tm_yday=9, tm_isdst=0)。

asctime() 方法將表示特定時間的元組或 struct_time(以 UTC 或本地時間表示)轉換為以下形式的 24 個字元的字串:'Mon Jan 9 10:51:77 2023'。在這個字串中,日期欄位分配了兩個字元,因此如果它是單數字符的日期,則會在其前面填充空格。

但是,與 asctime() C 函式不同,此方法不會向字串新增尾隨換行符。

語法

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

time.asctime([t]))

引數

  • t − (可選)這是一個包含 9 個元素的元組或 struct_time,表示 UTC 時間或本地時間。

返回值

此方法返回以下形式的 24 個字元的字串:'Tue Feb 17 23:21:05 2009'。

示例

以下示例顯示了 Python time asctime() 方法的用法。在這裡,我們嘗試使用 asctime() 方法將 localtime() 方法返回的印度當前本地時間表示為 24 個字元的字串格式。

import time

t = time.localtime()
lc = time.asctime(t)
print("Current local time represented in string:", lc)

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

Current local time represented in string: Mon Jan  9 11:07:30 2023

示例

此方法還將 UTC 時間轉換為字串格式。

在此示例中,使用 gmtime() 方法檢索當前 UTC 時間,並將此 UTC 時間作為引數傳遞給 asctime() 方法。當前時間從 struct_time 物件轉換為 24 個字元的字串。

import time

t = time.gmtime()
gm = time.asctime(t)
print("Current UTC time represented in string:", gm)

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

Current UTC time represented in string: Mon Jan  9 06:05:52 2023

示例

如果未將任何引數傳遞給此方法,則結果字串預設表示本地時間。

import time

ct = time.asctime()
print("Current time represented in string is", ct)

Current time represented in string is Mon Jan  9 11:40:07 2023

示例

從 localtime() 和 gmtime() 方法獲得的返回值是 struct_time 物件的形式;要將此方法的引數作為元組傳遞,必須像下面的示例中那樣手動建立它。

import time

# Create a tuple representing the current local time
t = (2023, 1, 9, 11, 40, 57, 0, 9, 0)

# Pass this tuple as an argument to the method
ct = time.asctime(t)

# Display the string output
print("Current local time represented in string", ct)

Current local time represented in string Mon Jan  9 11:40:57 2023
python_date_time.htm
廣告