Python ValueError:时间数据';abc xyz listener.log.2016-10-18-180001';与格式不匹配';%Y-%m-%d';
我有一个包含日期的字符串,我试图将日期格式与strtime()匹配,但它抛出了以下错误Python ValueError:时间数据';abc xyz listener.log.2016-10-18-180001';与格式不匹配';%Y-%m-%d';,python,datetime,strptime,Python,Datetime,Strptime,我有一个包含日期的字符串,我试图将日期格式与strtime()匹配,但它抛出了以下错误 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> dateti
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'
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
datetime.datetime.strtime(“abc xyz listener.log.2016-10-18-180001”,%Y-%m-%d”)
文件“C:\Python27\lib\\\\\\\\\ strtime.py”,第325行,在\\ strtime中
(数据字符串,格式))
ValueError:时间数据“abc xyz listener.log.2016-10-18-180001”与格式“%Y-%m-%d”不匹配
谁能帮我一下我哪里做错了。提前感谢错误消息非常清楚:
“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
如果re.search
无法在输入字符串中找到有效日期,您可能还需要添加一些try except