2016-11-16 64 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无法找到输入字符串有效日期。