Search code examples
pythondatetimestrptime

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


I have string which contains a date and i am trying to match date format with strptime() but its throwing following error.

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

I am getting the following :

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'

Can someone help me where i am doing mistake. Thanks in advance


Solution

  • The error message is pretty clear: "abc-xyz-listener.log.2016-10-18-180001" is not in the format of "%Y-%m-%d". There is not really much more to add.

    You can get rid of the extra stuff with regex:

    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
    

    You may also want to add some try-except in case re.search is not able to find a valid date in the input string.