Answer a question

The default format of csv is dd/mm/yyyy. When I convert it to datetime by df['Date']=pd.to_datetime(df['Date']), it change the format to mm//dd/yyyy.

Then, I used df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%d/%m/%Y') to convert to dd/mm/yyyy, But, they are in the string (object) format. However, I need to change them to datetime format. When I use again this (df['Date']=pd.to_datetime(df['Date'])), it gets back to the previous format. Need your help

Answers

You can use the parse_dates and dayfirst arguments of pd.read_csv, see: the docs for read_csv()

df = pd.read_csv('myfile.csv', parse_dates=['Date'], dayfirst=True)

This will read the Date column as datetime values, correctly taking the first part of the date input as the day. Note that in general you will want your dates to be stored as datetime objects.

Then, if you need to output the dates as a string you can call dt.strftime():

df['Date'].dt.strftime('%d/%m/%Y')
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐