Python 3 – time strptime() 方法
Python 3 標準庫中的 time 模塊提供了 strptime() 方法,可以將字符串轉換為時間類型。愛掏網 - it200.com該方法將字符串和格式化描述符作為輸入,按照給定的格式返回一個時間元組。愛掏網 - it200.com
時間元組 (struct_time) 包含了 year, month, day, hour, minute, second, weekday, 和 Julian day 等。愛掏網 - it200.com元組的函數是 time() 和 gmtime(),可以用來獲取當前時間或 UTC 時間。愛掏網 - it200.com
語法
time.strptime(string[, format])
參數:
- string — 待轉換為時間類型的字符串。愛掏網 - it200.com
- format — 數據字符串格式。愛掏網 - it200.com
返回值:
返回 struct_time 時間元組。愛掏網 - it200.com
示例
下面的示例展示了如何使用 strptime() 方法來將字符串轉換為時間元組:
import time
pt = time.strptime("21 Oct 2021", "%d %b %Y")
print("time tuple:", pt)
輸出:
time tuple: time.struct_time(tm_year=2021, tm_mon=10, tm_mday=21, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=294, tm_isdst=-1)
如上例所示,將字符串 “21 Oct 2021” 和格式描述符 “%d %b %Y” 作為參數傳入 strptime() 方法。愛掏網 - it200.com輸出結果為一個時間元組,其中包含了年、月、日等時間信息。愛掏網 - it200.com
下面是一些常用的時間格式描述符,用于將字符串轉換為時間元組:
格式化描述符 | 說明 |
---|---|
%Y | 年份 |
%m | 月份 |
%d | 一個月的第幾天 |
%H | 24 小時制的小時數 |
%M | 分鐘數 |
%S | 秒數 |
%a | 星期幾(縮寫) |
%A | 星期幾(全拼) |
%b | 月份(縮寫) |
%B | 月份(全拼) |
%c | 日期時間的字符串表示(如:06/01/01 17:22:21) |
%p | am 或 pm |
下面的示例將一個時間字符串按指定格式解析為時間元組:
import time
fmt = "%Y-%m-%d %H:%M:%S"
t_str = "2021-10-21 15:23:10"
pt = time.strptime(t_str, fmt)
print("time tuple:", pt)
輸出:
time tuple: time.struct_time(tm_year=2021, tm_mon=10, tm_mday=21, tm_hour=15, tm_min=23, tm_sec=10, tm_wday=3, tm_yday=294, tm_isdst=-1)
錯誤處理
如果輸入的字符串和數據格式不匹配,會拋出 ValueError 異常。愛掏網 - it200.com下面的示例展示了一個錯誤的格式化字符串:
import time
try:
# 嘗試解析錯誤的時間格式字符串
pt = time.strptime("2021-10-21 15:23:10", "%Y/%m/%d %H:%M:%S")
except ValueError:
print("Error: invalid format")
輸出:
Error: invalid format
結論
strptime() 方法十分實用,可以將字符串按照指定格式轉換為時間元組,為我們在 Python 中操作時間提供了方便。愛掏網 - it200.com在使用該方法時需要注意輸入的字符串和格式描述符是否匹配,否則會拋出異常。愛掏網 - it200.com