简体   繁体   中英

How to convert the date format in a dataframe using Python?

I have a data frame that consists of various columns, one of which consists of dates. Currently, the dates are in mm/dd/yyyy and I need to have them changed into dd/mm/yyyy.

The original dataset has 478 rows. I created a for loop to change the date format and overwrite onto the original cell value, to be able to have the new date format in the cell.However, the for loop I created, it changes the actual date into a different date in the original rows and then appends a brand new row with the converted date. After running the loop, the data frame grows from 478 to 800 rows.

When I run it line by line, I can see that the date gets converted correctly. I am unsure why when the final df is printed, it not only shows completely different dates but also additional rows with NaN values in other columns and the converted dates.

row = 0
for i in df['date']:
    x = i[3:5]+'-'+i[0:2]+'-'+i[6:10]
    df.loc['date'] = x 
    row += 1;
print (df)
import pandas as pd
dates = ['05/01/2021','05/02/2021','05/03/2021','05/04/2021','05/05/2021']
values = [1,2,3,4,5]

df = pd.DataFrame({'dates': dates,
               'values': values})

df['to_datetime'] = pd.to_datetime(df['dates'])

# this is converted date
df['target_date'] = '0'+ df['to_datetime'].dt.day.astype(str) + '/' + \
'0'+ df['to_datetime'].dt.month.astype(str) + '/' + 
df['to_datetime'].dt.year.astype(str)

Use datetime library to convert the date format and use lambda function to avoid looping through all of the values.

Try using this:

from datetime import datetime
df["date"] = df["date"].apply(lambda x: x.strftime("%d/%m/%Y"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM