ValueError: time data 'abc-xyz-listener.log.2016-10-18-180001' does not match format '%Y-%m-%d'

ValueError: time data 'abc-xyz-listener.log.2016-10-18-180001' does not match format '%Y-%m-%d'

我有一个包含日期的字符串,我正在尝试将日期格式与 strptime() 匹配,但它抛出以下错误。

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'

谁能帮我看看我做错了什么。提前致谢

错误信息很清楚:"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 无法在输入字符串中找到有效日期。