2016-11-16 67 views
-1

我有一個包含日期的字符串,我試圖使用strptime()匹配日期格式,但拋出以下錯誤。ValueError:時間數據'abc-xyz-listener.log.2016-10-18-180001'與格式不匹配'%Y-%m-%d'

import datetime 
datetime.datetime.strptime("abc-xyz-listener.log.2016-10-18-180001", "%Y-%m-%d") 

我得到以下幾點:

Traceback (most recent call last): 
    File "<pyshell#3>", line 1, in <module> 
    datetime.datetime.strptime("abc-xyz-listener.log.2016-10-18-180001", "%Y-%m-%d") 
    File "C:\Python27\lib\_strptime.py", line 325, in _strptime 
    (data_string, format)) 
ValueError: time data 'abc-xyz-listener.log.2016-10-18-180001' does not match format '%Y-%m-%d' 

有人可以幫助我在哪裏,我在做什麼錯誤。在此先感謝

回答

2

錯誤消息很明顯:"abc-xyz-listener.log.2016-10-18-180001"不是格式"%Y-%m-%d"。沒有什麼更多要補充的。

你可以用正則表達式擺脫多餘的東西:

import re 
import datetime 

string = 'abc-xyz-listener.log.2016-10-18-180001' 

date_string = re.search(r'\d{4}-\d{2}-\d{2}', string).group() 

print(date_string) 
# 2016-10-18 

print(datetime.datetime.strptime(date_string , "%Y-%m-%d")) 
# 2016-10-18 00:00:00 

您可能還需要添加一些try-except萬一re.search無法找到輸入字符串有效日期。