我有以下字串 20211208_104755,代表 date_time 格式。我想使用 datetime.strip() 方法將其轉換為 python 日期時間格式。
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%y/%m/%d')
但是我收到以下錯誤。
ValueError: time data '20211208' does not match format '%y/%m/%d'
uj5u.com熱心網友回復:
strptime 中的第二個引數必須與您的日期時間字串的模式相匹配。您可以在https://docs.python.org/3/library/datetime.html上找到模式及其含義
在您的情況下,您可以將其格式化為
from datetime import datetime
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%Y%m%d_%H%M%S')
print(datetime_object)
>>> 2021-12-08 10:47:55
uj5u.com熱心網友回復:
應該做的是定義mydatetime字串的組成方式。示例:
在此處%Y is the year (4 digits);檢查格式(部分 strftime() 日期格式代碼)
所以在你的例子中,我假設它是這樣的:
mydatetime = "20211208_104755"
datetime_object = datetime.strptime(mydatetime, '%Y%m%d_%H%M%S')
print (datetime_object)
結果
2021-12-08 10:47:55
和
type(datetime_object)
datetime.datetime
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/516243.html
