How to remove the colon from formatted time value in a dataframe?

Question:

I have a column named "Start Time". It is a string and it displays the time as 11:20:15. I want to have the time in the format 112015. So I need to replace the colon.

I have tried:

["Start Time"] = df["Start Time"].replace(":","", regex=True)

But that didn’t work. It didn’t give an error either but the time remains 11:20:15.

Can someone point me in the right direction?

Asked By: Sj03rd

||

Answers:

You need to add .str to handle each value as a str and apply .replace() (documentation) :

df["Start Time"] = df["Start Time"].str.replace(":","")
Answered By: F Blanchet

Is the df["Start Time"] column a string datatype? Often pandas will read in dates as datetime objects. You can check this by printing df.dtypes and see if it says object for this column.

Then I’d recommend using df.strftime (string formatter) as done here: How to change the datetime format in pandas if you really want the string in the format you mentioned.

Answered By: Lourens

Looks like you have a datatime object in Start Time column. Use dt.strftime(%H%M%S)

Ex:

df["Start Time"].dt.strftime(%H%M%S)
Answered By: Rakesh

When I did:

df['Start Time'] = df['Start Time'].astype(str)

And then:

["Start Time"] = df["Start Time"].replace(":","", regex=True)

It worked perfectly. Thank you all for thinking with me!

Answered By: Sj03rd
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.