2

I read an excel in pandas like this

df = pd.read_excel("Test.xlsx", index_col=[0])

The dataframe look like this with the index containing a date and time and one column:

01.01.2015 00:15:00     47.2
01.01.2015 00:30:00     46.6
01.01.2015 00:45:00     19.4
01.01.2015 01:00:00     14.8
01.01.2015 01:15:00     14.8
01.01.2015 01:30:00     16.4
01.01.2015 01:45:00     16.2
...

I want to convert the index to a datatimeindex, I tried

df.index = pd.to_datetime(df.index)

and got: "ValueError: Unknown string format"

What is here the best way to convert the index to a datatime format containing date and tiem to use datetime based functions

1 Answer 1

1

I think you need add parameter format - see http://strftime.org/:

df.index = pd.to_datetime(df.index, format='%d.%m.%Y %H:%M:%S')

print (df)
                        a
2015-01-01 00:15:00  47.2
2015-01-01 00:30:00  46.6
2015-01-01 00:45:00  19.4
2015-01-01 01:00:00  14.8
2015-01-01 01:15:00  14.8
2015-01-01 01:30:00  16.4
2015-01-01 01:45:00  16.2
Sign up to request clarification or add additional context in comments.

5 Comments

I tried that also, but got: "ValueError: unconverted data remains: b" ???
It seems you have bad data - you can check all rows which cannot be converted to datetimeindex by print (df[pd.to_datetime(df.index, format='%d.%m.%Y %H:%M:%S', errors='coerce').to_series().isnull().values]). What return it?
Thgen you can replace all bad values by NaT by df.index = pd.to_datetime(df.index, format='%d.%m.%Y %H:%M:%S', errors='coerce')
ok, you´re right, bad data, didnt recognize that. I deleted that data, now it works.
Thanks a lot for help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.