介紹
Python的datetime
和time
模組都包含一個strptime()
類別方法,用於將字串轉換為物件。
在本文中,您將使用strptime()
將字串轉換為datetime
和struct_time()
物件。
使用DigitalOcean App Platform從GitHub部署您的Python應用程式。讓DigitalOcean專注於擴展您的應用程式。
使用datetime.strptime()
將字串轉換為datetime
物件
datetime.strptime(date_string, format)
有關datetime.strptime()
中使用的格式指令的詳細信息,請參閱Python文檔中的strftime()
和strptime()
格式代碼。
將字符串轉換為 datetime.datetime()
對象的示例
以下示例將日期和時間字符串轉換為 datetime.datetime()
對象,並打印結果對象的類名和值:
from datetime import datetime
datetime_str = '09/19/22 13:55:26'
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S')
print(type(datetime_object))
print(datetime_object) # 在默認格式中打印
輸出為:
<class 'datetime.datetime'>
2022-09-19 13:55:26
將字符串轉換為 datetime.date()
對象的示例
以下示例將日期字符串轉換為 datetime.date()
對象,並打印結果對象的類型和值:
from datetime import datetime
date_str = '09-19-2022'
date_object = datetime.strptime(date_str, '%m-%d-%Y').date()
print(type(date_object))
print(date_object) # 在默認格式中打印
輸出為:
<class 'datetime.date'>
2022-09-19
將字符串轉換為 datetime.time()
對象的示例
以下示例將時間字符串轉換為datetime.time()
對象,並打印結果對象的類型和值:
from datetime import datetime
time_str = '13::55::26'
time_object = datetime.strptime(time_str, '%H::%M::%S').time()
print(type(time_object))
print(time_object)
輸出如下:
<class 'datetime.time'>
13:55:26
使用區域示例將字符串轉換為datetime.datetime()
對象
以下示例將德國區域日期字符串轉換為datetime.datetime()
對象,並打印結果對象的類型和值:
from datetime import datetime
import locale
locale.setlocale(locale.LC_ALL, 'de_DE')
date_str_de_DE = '16-Dezember-2022 Freitag' # de_DE區域
datetime_object = datetime.strptime(date_str_de_DE, '%d-%B-%Y %A')
print(type(datetime_object))
print(datetime_object)
輸出如下:
<class 'datetime.datetime'>
2022-12-16 00:00:00
請注意,結果對象不包括輸入字符串的星期幾名稱,因為datetime.datetime()
對象僅將星期幾作為十進制數字包含。
使用time.strptime()
將字符串轉換為struct_time()
對象
time.strptime()
方法的語法如下:
time.strptime(time_string[, format])
time.strptime()
方法返回与由 time_string 解析的 format 匹配的 time.struct_time()
对象。需要提供 time_string,且两个参数必须为字符串。如果未提供 format,默认为:
'%a %b %d %H:%M:%S %Y'
这对应于 ctime()
函数返回的格式。
格式指令对于 time.strptime()
和 time.strftime()
相同。在 Python 文档中了解有关 time
模块的 格式指令 的更多信息。
使用提供的格式将字符串转换为 struct_time()
对象的示例
以下示例通过提供 format 参数将时间字符串转换为 time.struct_time()
对象,并打印结果对象的值:
import time
time_str = '11::33::54'
time_obj = time.strptime(time_str, '%H::%M::%S')
print("A time.struct_time object that uses the format provided:")
print(time_obj)
输出为:
A time.struct_time object that uses the format provided:
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1,
tm_hour=11, tm_min=33, tm_sec=54, tm_wday=0, tm_yday=1,
tm_isdst=-1)
如输出所示,当将字符串转换为 time.struct_time()
对象时,strptime()
方法对于在 format 参数中未定义的任何格式指令都使用占位符值。
將字串轉換為struct_time()
物件使用預設格式範例
如果在將時間字串轉換為time.struct_time()
物件時沒有提供格式參數,則會使用預設格式,如果輸入字串與預設格式不完全匹配,則會產生錯誤:
'%a %b %d %H:%M:%S %Y'
以下範例將時間字串轉換為time.struct_time()
物件,未提供格式參數,並列印結果物件的值:
import time
# 預設格式 - "%a %b %d %H:%M:%S %Y"
time_str_default = 'Mon Dec 12 14:55:02 2022'
time_obj_default = time.strptime(time_str_default)
print("A time.struct_time object that uses the default format:")
print(time_obj_default)
輸出為:
A time.struct_time object that uses the default format:
time.struct_time(tm_year=2022, tm_mon=12, tm_mday=12,
tm_hour=14, tm_min=55, tm_sec=2, tm_wday=0, tm_yday=346,
tm_isdst=-1)
如輸出所示,當將字串轉換為time.struct_time()
物件時,strptime()
方法會對任何未在格式參數中定義的格式指令使用佔位符值,或者如果未提供格式則使用預設格式。
解決strptime()
錯誤
如果輸入字串無法使用提供的格式進行 strptime()
解析,則會引發 ValueError
。您可以使用 try
區塊來測試解析錯誤,以及使用 except
區塊來列印結果。當您使用 strptime()
方法時獲得的 ValueError
訊息清楚地解釋了解析錯誤的根本原因。以下示例演示了一些常見錯誤,例如多餘的資料和格式不匹配:
from datetime import datetime
import time
datetime_str = '09/19/18 13:55:26'
try:
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y')
except ValueError as ve1:
print('ValueError 1:', ve1)
time_str = '99::55::26'
try:
time_object = time.strptime(time_str, '%H::%M::%S')
except ValueError as ve2:
print('ValueError 2:', ve2)
輸出為:
ValueError 1: unconverted data remains: 13:55:26
ValueError 2: time data '99::55::26' does not match format '%H::%M::%S'
結論
在本教程中,您使用 Python 將日期和時間字串轉換為 datetime
和 time
物件。繼續閱讀更多有關 Python 教程 的學習內容。
Source:
https://www.digitalocean.com/community/tutorials/python-string-to-datetime-strptime