Home > Software design >  Converting pandas index to datetime
Converting pandas index to datetime

Time:04-09

I have the following datetime string in pandas index:

2022-04-04T09:15:00-05:00

I am trying to convert this to a datetime object with this:

pd.to_datetime(df.index).strftime('%Y-%m-%dT%H:%M:%S')

But for some reason the index value is this:

Index(['1970-01-01T00:00:00',

Could you please advise as to why it is not recognizing the dates?

CodePudding user response:

Your actual index being converted is 0. If you do:

df=pd.DataFrame([1])
df.index=[0]
pd.to_datetime(df.index).strftime('%Y-%m-%dT%H:%M:%S')

You will see that:

1970-01-01 00:00:00.000000000

actually corresponds to 0 in Datetime format.

My guess is that you need to df.set_index to your date string before calling

pd.to_datetime(df.index).strftime('%Y-%m-%dT%H:%M:%S')
  • Related