介紹 Python 的 time 時間模組中各函數的使用方法與範例。
time.time() 函數
time.time() 可以傳回從 1970/1/1 00:00:00 算起至今的秒數:
# 引入 time 模組
import time
# 從 1970/1/1 00:00:00 至今的秒數
seconds = time.time()
# 輸出結果
print(seconds)
1569376996.8464663
time.time() 通常是用來作為時間戳記,例如測量程式執行時間。
time.ctime() 函數
time.ctime() 函數可以將 time.time() 所產生的秒數,轉換為本地時間:
# 引入 time 模組
import time
# 從 1970/1/1 00:00:00 至今的秒數
seconds = time.time()
# 將秒數轉為本地時間
local_time = time.ctime(seconds)
# 輸出結果
print("本地時間:", local_time)
本地時間: Wed Sep 25 10:17:09 2019
如果不加任何參數,time.ctime() 會直接採用目前的時間:
# 引入 time 模組
import time
# 現在時間
now = time.ctime()
# 輸出結果
print("現在時間:", now)
現在時間: Wed Sep 25 10:21:35 2019
time.sleep() 函數
time.sleep() 可以讓程式暫停指定的秒數:
# 引入 time 模組
import time
print("Hello")
# 暫停 1.5 秒
time.sleep(1.5)
print("World")
time.localtime() 函數
time.localtime() 可以將 time.time() 所產生的秒數,轉換為 struct_time 格式的本地時間。
import time
# 轉換為 struct_time 格式的本地時間
result = time.localtime(1569376996)
# 輸出結果
print("結果:", result)
結果: time.struct_time(tm_year=2019, tm_mon=9, tm_mday=25, tm_hour=10, tm_min=3, tm_sec=16, tm_wday=2, tm_yday=268, tm_isdst=0)
struct_time 格式的好處就是可以直接取出日期或時間裡面的任意數值:
# 輸出日期與時間
print("年:", result.tm_year)
print("月:", result.tm_mon)
print("日:", result.tm_mday)
print("時:", result.tm_hour)
print("分:", result.tm_min)
print("秒:", result.tm_sec)
print("星期幾:", result.tm_wday) # 0 代表星期一
年: 2019 月: 9 日: 25 時: 10 分: 3 秒: 16 星期幾: 2
time.gmtime() 函數
time.gmtime() 函數的用途跟 time.localtime() 函數類似,只不過它傳回的時間是世界協調時間(UTC):
import time
# 轉換為 struct_time 格式的本地時間
result = time.gmtime(1569376996)
# 輸出結果
print("結果:", result)
結果: time.struct_time(tm_year=2019, tm_mon=9, tm_mday=25, tm_hour=2, tm_min=3, tm_sec=16, tm_wday=2, tm_yday=268, tm_isdst=0)
time.mktime() 函數
time.mktime() 函數跟 time.localtime() 互為反函數,可將 struct_time 格式的時間轉為秒數:
import time
# 將秒數轉換為 struct_time 格式
t = time.localtime(1569376996)
# 將 struct_time 格式轉換為秒數
s = time.mktime(t)
# 輸出結果
print(s)
1569376996.0
time.asctime() 函數
time.asctime() 函數可將 struct_time 格式的時間轉為文字:
import time
# 將秒數轉換為 struct_time 格式
t = time.localtime(1569376996)
# 將 struct_time 格式轉換為文字
result = time.asctime(t)
# 輸出結果
print(result)
Wed Sep 25 10:03:16 2019
time.strftime() 函數
time.strftime() 函數可以依照指定的格式將 struct_time 時間資料轉換為文字輸出:
import time
# 取得 struct_time 格式的時間
t = time.localtime()
# 依指定格式輸出
result = time.strftime("%m/%d/%Y, %H:%M:%S", t)
print(result)
09/25/2019, 14:57:52
關於各種格式的用法,請參考 time 模組的官方文件。
time.strptime() 函數
time.strptime() 函數則是跟 time.strftime() 函數相反,它是依據指定的格式,解析文字資料中的時間,輸出 struct_time 格式的時間:
import time
# 文字資料
time_string = "09/25/2019, 14:57:52"
# 依指定格式解析文字資料中的時間,輸出 struct_time 格式的時間
result = time.strptime(time_string, "%m/%d/%Y, %H:%M:%S")
print(result)
time.struct_time(tm_year=2019, tm_mon=9, tm_mday=25, tm_hour=14, tm_min=57, tm_sec=52, tm_wday=2, tm_yday=268, tm_isdst=-1)
