Home > front end >  How do I convert object type data to datetime data in this case?
How do I convert object type data to datetime data in this case?

Time:05-13

So I have data given in the format of: 1/1/2022 0:32

I looked up the type that was given with dataframe.dytpe and found out that this was an object type. Now for my further analysis I think it would be best to get this converted to a datetime data type.

In order to do so, I tried using

dataframe["time"] = pd.to_datetime(["time"], format = "%d%m%y")

, though that just leaves me with NaT showing up in the rows where I want my time to appear. What is the correct way to convert my given data? Would it be better to split time and date or is there a way to convert the whole?

CodePudding user response:

You can do like this:

df['time'] = pd.to_datetime(df['time']).dt.normalize()

or

df["time"]=df["time"].astype('datetime64')

it will convert object type to datetime64[ns]

I think datetime64[ns] is always in YYYY-MM-DD format, if you want to change your format you can use:

df['time'] = df['time'].dt.strftime('%m/%d/%Y') 

You can change the '%m/%d/%Y'according to your desired format. But, The datatype will again change to object by using strftime.

  • Related