1

A column in the dataframe looks like DD/MM/YYYY format.

I want to slice it and rearrange to MM/DD/YYYY (for calculation)

I have tried:

import pandas as pd
from io import StringIO

csvfile = StringIO("""
DD/MM/YYYY
01/05/2020
21/02/2021
19/06/2021
05/06/2021
11/06/2021
10/05/2021
")

df = pd.read_csv(csvfile, sep = ',', engine='python')

df['DD/MM/YYYY'] = df['DD/MM/YYYY'].astype(str)

df['MM/DD/YYYY'] = df['DD/MM/YYYY'][3:5] + '/' + df['DD/MM/YYYY'][:2] + '/' + df['DD/MM/YYYY'][-4:]

# df['MM/DD/YYYY'] = pd.to_datetime(df['DD/MM/YYYY'][3:5] + '/' + df['DD/MM/YYYY'][:2] + '/' + df['DD/MM/YYYY'][-4:])

print (df)

But it doesn't work. What would be the right way to write it? Thank you!

1 Answer 1

1

Use .str:

df['MM/DD/YYYY'] = df['DD/MM/YYYY'].str[3:5] + '/' + df['DD/MM/YYYY'].str[:2] + '/' + df['DD/MM/YYYY'].str[-4:]

If possible you can parse datetimes by original format in specified in format='%d/%m/%Y' and then add Series.dt.strftime:

df['MM/DD/YYYY']  = pd.to_datetime(df['DD/MM/YYYY'], format='%d/%m/%Y').st.strftime('%m/%d/%Y')
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.