0

One of the columns in my pandas dataframe looks like this:

14.3.2019
15.3.2019
16.3.2019

So this is European/German date that I have to convert to USA format:

2019-3-14
2019-3-15
2019-3-16

What is the fastest way to do it, possibly inplace, if I have a large dataset?

8
  • 1
    pd.to_datetime(df['date'], format='%d.%m.%Y').strftime('%Y-%m-%d')? Commented Nov 15, 2019 at 15:58
  • 1
    pd.to_datetime(df['date_col']) ? Commented Nov 15, 2019 at 15:59
  • @QuangHoang : AttributeError: 'Series' object has no attribute 'strftime' Commented Nov 15, 2019 at 16:01
  • 2
    add .dt: pd.to_datetime(...).dt.strftime? But, as suggested by @anky_91, don't use string, just use datetime format, i.e., use pd.to_datetime only. Commented Nov 15, 2019 at 16:02
  • 1
    @Harvey much faster than what? The difference between my suggestion and anky's is that I pass the format so pandas doesn't need to guess. If you have consistent format, then that's the way to go. Commented Nov 15, 2019 at 16:10

1 Answer 1

2

Correct answer given by both commenters, posting here faster solution from @QuangHoang.

Casting string column in date type in desired format:

df['date'] = pd.to_datetime(df['date'], format='%d.%m.%Y').dt.strftime('%Y-%m-%d')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.