-1

I have a dataframe with a column called date, formatted as string and it looks like this:

date
20200109
20200304
20210112

Is there a way I can format that into datetime?

1

1 Answer 1

3

You can use pd.to_datetime with custom format=:

df["date"] = pd.to_datetime(df["date"], format="%Y%d%m")  # use "%Y%m%d" if month is first
print(df)

Prints:

        date
0 2020-09-01
1 2020-04-03
2 2021-12-01

Note: datetime format cheatsheet

Sign up to request clarification or add additional context in comments.

3 Comments

Are you sure it's %Y%d%m and not %Y%m%d?
@gre_gor That I'm not sure. But hopefully OP knows the correct order and changes the format= string accordingly.
It is Y%m%d, but I sorted that out! TY

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.