Page cover image

time 【時間】

struct_time


gmtime()localtime()strptime() 返回的時間值序列的類型。 它是一個 named tuple interface 物件:可以透過索引和屬性名稱訪問值。存在以下值:

Index
Attribute
Values

0

tm_year

any value

1

tm_mon

range [1, 12]

2

tm_mday

range [1, 31]

3

tm_hour

range [0, 23]

4

tm_min

range [0, 59]

5

tm_sec

range [0, 61]60 在表示閏秒的時間戳中有效。由於向後兼容,所以保留 61

6

tm_wday

range [0, 6]

7

tm_yday

range [1, 366]

8

tm_isdst

0, 1 or -1; -1 表示由 library 自動確定 DST (Daylight Saving Time)。

N/A

tm_zone

時區名稱的縮寫

N/A

tm_gmtoff

UTC offsets (seconds)

當長度不正確的 Tuple 或錯誤類型,傳遞給需要 struct_time 的函數時,會引發 TypeError。

asctime(), ctime()


asctime([t])struct_time 物件,轉換為表示本地的時間和日期。 如果您沒有提供 t,它將使用 localtime() 返回的本地的當前時間。

ctime([secs]) 將 Epoch ,轉換為當前的時間和日期。如果未提供 secssecs=None ,則使用 time() 返回的當前時間。 ctime(secs) 相當於 asctime(localtime(secs))

紀元 (Epoch)。

表示自 1970 年 1 月 1 日 00:00:00 UTC 以來經過的總秒數 (浮點數)。這是許多系統中存儲時間的常用方法,因為它很簡單 (只是一個數字)並且可以高精度地表示任何日期和時間。

浮點數 (float)。

float 所能表示的最大值約為 1.8e308,最小值約為 2.2e-308。因此,Epoch 的最大值將約為 1.8e308 秒,即約 584 年 (即西元2554年)。

PYTHON
'''asctime()'''
import time

# Get Current time
print(time.asctime())

# =========================================================
# Get time in seconds since the epoch
seconds = time.time()

# Convert to struct_time
time_struct = time.localtime(seconds)

# Convert to a string
time_str = time.asctime(time_struct)
print(time_str)

# =========================================================
# July 20, 1969, 20:17 UTC, when man first landed on the moon
timestamp = 14182900

# Convert to a struct_time in UTC
time_struct = time.gmtime(timestamp)

# Convert to a String
print(time.asctime(time_struct))

執行結果:

Fri Jul  7 19:03:15 2023
Fri Jul  7 19:03:15 2023
Sun Jun 14 03:41:40 1970

PYTHON
'''ctime()'''
mport time

# Gives current time
print(time.ctime())

# July 20, 1969, 20:17 UTC, when man first landed on the moon
timestamp = 14182900
print(time.ctime(timestamp))

執行結果:

Output: Fri Jul  7 17:13:47 2023
Output: Sun Jun 14 03:41:40 1970

gmtime(), localtime(), mktime()


gmtime([secs]) 將 Epoch ,轉換為 UTC (Coordinated Universal Time) 格式的 struct_time 物件。如果未提供 secs,它將返回 UTC 時間。

localtime([secs])gmtime() 類似,但轉換為本地時間。

mktime(t)localtime() 的反函數。參數 t 是 struct_time 或完整的 9-Tuple。它返回一個浮點數,以與 time() 兼容。

PYTHON
import time

# 【gmtime()】
# Getting current time
utc_time = time.gmtime()
print(utc_time)

# Formatting the time
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", utc_time)
print(formatted_time)

# =========================================================
# 【localtime()】
# Getting local time
local_time = time.localtime()
print(local_time)

# Formatting the time
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print(formatted_time)

執行結果:

time.struct_time(tm_year=2023, tm_mon=7, tm_mday=7, 
tm_hour=11, tm_min=11, tm_sec=11, tm_wday=4, tm_yday=188, tm_isdst=0)
2023-07-07 11:11:11

time.struct_time(tm_year=2023, tm_mon=7, tm_mday=7, 
tm_hour=19, tm_min=11, tm_sec=11, tm_wday=4, tm_yday=188, tm_isdst=0)
2023-07-07 19:11:11

PYTHON
'''mktime()'''
import time

# =========================================================
# 【Converting the current time to epoch time】

# Get the current time
now = time.localtime()

# convert struct_time to epoch time
epoch_time = time.mktime(now)
print("Epoch time:", epoch_time)

# =========================================================
# 【Converting a specific time to epoch time】

# Define a time tuple
time_tuple = (2023, 7, 7, 15, 30, 0, 4, 188, -1)  # July 7, 2023, 15:30:00

# convert the time tuple to epoch time
epoch_time = time.mktime(time_tuple)
print("Epoch time:", epoch_time)

# =========================================================
# 【Comparing two dates】

# Define two time tuples
time_tuple1 = (2023, 7, 7, 15, 30, 0, 4, 188, -1)  # July 7, 2023, 15:30:00
time_tuple2 = (2023, 8, 7, 15, 30, 0, 1, 219, -1)  # August 7, 2023, 15:30:00

# Convert the time tuples to epoch time
epoch_time1 = time.mktime(time_tuple1)
epoch_time2 = time.mktime(time_tuple2)

# Compare the epoch times
print("Time difference in seconds:", epoch_time2 - epoch_time1)

執行結果:

Epoch time: 1688727762.0
Epoch time: 1688715000.0
Time difference in seconds: 2678400.0

strftime(), strptime()


strftime(format[, t])struct_time 物件轉換為 format 指定的 String。 format 詳見:strftime()。 如果未提供 t,則使用 localtime() 返回的當前時間。 format 必須是字符串。

strptime(string[, format]) 根據 format 解析表示時間的 string,返回 struct_time 物件。

strftime() 是按照作業系統實現的,因此有時可以提供比原始文檔更多的指令。 但 strptime() 是獨立作業系統的,因此不一定支援所有未記錄的可用指令。

time module 的 struct_time 不夠複雜,無法計算不同年份的日期之間的天數,為此我們可以使用使用 datetime module。

PYTHON
'''strptime()'''
import time

t = time.gmtime()
print(t) 

# =========================================================
# Extract specific values
t = time.localtime()
print(f"Year: {t.tm_year}")
print(f"Month: {t.tm_mon}")
print(f"Day of the week: {t.tm_wday}")

# Extract specific values (using indices)
print(f"Year: {t[0]}")
print(f"Month: {t[1]}")
print(f"Day of the week: {t[6]}")

# =========================================================
# Calculate the number of days between two dates
date1 = "2023-07-01"
date2 = "2023-07-07"

struct_time1 = time.strptime(date1, "%Y-%m-%d")
struct_time2 = time.strptime(date2, "%Y-%m-%d")

days_difference = struct_time2.tm_yday - struct_time1.tm_yday
print(f"The number of days between {date1} and {date2} is {days_difference}.")


# =========================================================
# Calculate the number of days between dates from different years
from datetime import datetime

date1 = "2023-07-01"
date2 = "2024-07-07"

# Convert strings to datetime objects
datetime1 = datetime.strptime(date1, "%Y-%m-%d")
datetime2 = datetime.strptime(date2, "%Y-%m-%d")

# Subtract datetimes and extract the number of days
days_difference = (datetime2 - datetime1).days
print(f"The number of days between {date1} and {date2} is {days_difference}.")

執行結果:

time.struct_time(tm_year=2023, tm_mon=7, tm_mday=7, 
tm_hour=13, tm_min=55, tm_sec=10, tm_wday=4, tm_yday=188, tm_isdst=0)

Year: 2023
Month: 7
Day of the week: 4
Year: 2023
Month: 7
Day of the week: 4

The number of days between 2023-07-01 and 2023-07-07 is 6.

The number of days between 2023-07-01 and 2024-07-07 is 372.

Last updated

Was this helpful?