GNZ
GNZ

Reputation: 595

What could be the reason of this error when using date time in Python?

I use Spyder with Python 3 for data analysis. I am reading date and time columns from a CSV file. The file contains the the columns for date and time as shown below:

04-09-20,16:32:56
04-09-20,16:32:57
04-09-20,16:32:58

So I have a date(in 04-09-20 format) and a time array in(16:32:56) format. To use the data and time together in a plot's axis I first combine these date and time arrays and then use pd.to_datetime() as follows:

date_combine_time = date + ' ' + t

date_time = pd.to_datetime(date_combine_time, format = "%d-%m-%Y %H:%M:%S")

plt.plot(date_time, values)

But I get the following error:

time data '04-09-20 16:32:56' does not match format '%d-%m-%Y %H:%M:%S' (match)

What could be wrong here?

Upvotes: 0

Views: 50

Answers (1)

RoadRunner
RoadRunner

Reputation: 26335

%Y is for 4 digit years. You need 2 digit years, which is %y. This means your format should change to "%d-%m-%y,%H:%M:%S". I also added the missing comma ,, since your date strings need to match the format exactly.

You can have a look at the Format Codes if you are unsure.

Upvotes: 2

Related Questions