Python Error: time data does not match format

I was using a CSV and took out a few dates then resaved it and suddenly my code that worked before did not work anymore. I tried referencing the old CSV and got the same error despite it running fine before. Here is what I had tried:

import numpy as np
import pandas as pd
Q = pd.read_csv("Data_V3.csv")
Q['date'] = pd.to_datetime(Q['date'], format='%m-%d-%Y')

The CVS looks like this:

date:     flow:
1/1/1930  1300

I also tried:

Q['date'] = pd.to_datetime(Q['date'], format='%Y-%m-%d')

The full error is: “ValueError: time data ‘1/1/1930’ does not match format ‘%m-%d-%Y’ (match)”

Thank you!

Answer

You need to use / instead of - in your code to match the format.

Q['date'] = pd.to_datetime(Q['date'], format='%m/%d/%Y')

When you read the error, it gives you some information you probably skip over when you read it:

“ValueError: time data ‘1/1/1930’ does not match format ‘%m-%d-%Y’ (match)”

That is an exact example of what broke your code. Then it gives you the format as well. The only difference that breaks it is a / from the example given.

Leave a Reply

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