2

I have Index like below:

Index(['2000-02-29 00:00:00_y', '2000-03-31 00:00:00_y',
       '2000-04-30 00:00:00_y', '2000-05-31 00:00:00_y',
       '2000-06-30 00:00:00_y', '2000-07-31 00:00:00_y',......

and tired to change in to datetime format by:

df.index.to_datetime())

now i am getting error :

ValueError: Unknown string format

how to solve this problem?

1 Answer 1

4

slice the str to remove the extraneous '_y' and then convert:

In[123]:
pd.to_datetime(index.str[:-2])

Out[123]: 
DatetimeIndex(['2000-02-29', '2000-03-31', '2000-04-30', '2000-05-31',
               '2000-06-30', '2000-07-31'],
              dtype='datetime64[ns]', freq=None)

Note that pd.Index.to_datetime() raises a DeprecationWarning so you should use the top-level to_datetime instead.

Note that by default the time component isn't displayed as it's equal to '00:00:00' but it is a full datetime:

In[124]:
pd.to_datetime(index.str[:-2])[0]

Out[124]: Timestamp('2000-02-29 00:00:00')
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @EdChum it helps :)

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.