How Do You Troubleshoot the Python Problem “ValueError: time data … does not match %m”?

Problem scenario
You are trying to parse a log file with Python. The date entries use abbreviated spellings of months -- not integer month values. You get an error like this:

"ValueError: time data 'Jul 15 06:10:32' does not match format '%m %d %H:%M:%S'"

What should you do?

Solution
Replace the "%m" with "%b".

import datetime
log_reader = open('auth.log', 'r')
for line in log_reader:
    dt_of_log = datetime.datetime.strptime(line[:15], '%b %d %H:%M:%S')
    if line.startswith("Jul 15"):
        print(line)

Leave a comment

Your email address will not be published. Required fields are marked *