KMFR
KMFR

Reputation: 935

Reformat a datetime column in pandas

I have a Pandas dataframe df containing datetimes and their respective values. Now I want to make some format changes to each datetime in the dataframe, but noticed that a normal for loop doesn't actually change anything in the dataframe.

This is what I tried, and also shows what I'm trying to do:

#original format of the datetimes: sunnuntai 1.1.2017 00:00

for i in df["Datetime"]:

#removes the string containing the weekday from the beginning
    i = re.sub("^[^ ]* ","", i) 

#converts 1.1.2017 00:00 into 2017-01-01 00:00
    i = datetime.datetime.strptime(i, "%d.%m.%Y %H:%M").strftime("%Y-%m-%d %H:%M")

How should I go about doing these format changes permanently? Thank you.

Upvotes: 1

Views: 549

Answers (1)

cs95
cs95

Reputation: 403258

Ditch the loop, aim to vectorize. I break down the steps —

  1. use str.split to get rid of leading text,
  2. pd.to_datetime with dayfirst=True for datetime conversion, and
  3. dt.strftime to convert the result to your format

df['Datetime'] = pd.to_datetime(
    df['Datetime'].str.split(n=1).str[1], dayfirst=True
).dt.strftime("%Y-%m-%d %H:%M")

Upvotes: 2

Related Questions