0

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?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Sj03rd
  • 61
  • 3
  • 10

4 Answers4

3

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

df["Start Time"] = df["Start Time"].str.replace(":","")
F Blanchet
  • 1,430
  • 3
  • 21
  • 32
0

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.

Lourens
  • 104
  • 1
  • 11
  • It is indeed a object. I will check the explanation in the link. Thank you – Sj03rd Jan 13 '20 at 09:40
  • Glad to help! Definitely do, getting familiar with handling dates is something that will save you a lot of time in the long run. – Lourens Jan 13 '20 at 09:42
  • Still trying here. I tried df['Start Time'] = df['Start Time'].dt.strftime(format='%H%M%S'), but then I get the error message "Can only use .dt accessor with datetimelike values". Does this mean that I have to change the dtype of this column to datetime? – Sj03rd Jan 13 '20 at 13:09
0

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)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

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!

Sj03rd
  • 61
  • 3
  • 10