tm553
tm553

Reputation: 97

Error when using pd.to_datetime to convert string dates to datetime format

I am having issues using the pd.to_datetime command to process dates that are being read from a csv file. When the csv is read, the format of the dates is as follows;

01/01/2015
02/01/2015
etc

I need to do some operations on the dates, so wanted to convert to datetime and did so using the following command on the df

wind.Date = pd.to_datetime(wind.Date).dt.date

After using this step, the wind.Date column of the dataframe has the following format;

2015-01-01
2015-02-01
etc etc

This is fine, excepting that at certain numbers (i.e above the 12th of each month) the format switches to;

2015-01-13

Which is obviously not consistent, and it reverts back once it gets to the beginning of the next month etc.

Thus, when using the date.month and date.year commands on this column with varying month and date ordering, this breaks down.

Any tips much appreciated.

Upvotes: 1

Views: 2316

Answers (2)

Ami Tavory
Ami Tavory

Reputation: 76297

You can control the date format in pd.to_datetime and pd.Series.dt.date:

pd.to_datetime(wind.Date, format="%d/%m/%Y").dt.date.strftime('%Y-%m-%d')

for example.

Upvotes: 2

Toby Petty
Toby Petty

Reputation: 4660

You need to specify the format of the string datetimes to make sure the dates are read as expected, as in:

pd.to_datetime(wind.Date, format="%d/%m/%Y")

For more information see the function documentation, and date string formatting reference.

Upvotes: 1

Related Questions