简体   繁体   中英

How to change date from “yyyy-mm-dd” to “mm/dd/yyyy” in Python?

I have a column in my Excel file (before importing into IDE with read_csv) with dates that begin as string type with the format of “yyyy-mm-dd” and I need to change that entire column to date type with format of “mm/dd/yyyy” as I'm importing it as a data frame in Python with Pandas.

Also, it would be great if the format could be where if the month and/or day is a single digit, then it comes out like “1/4/2021”. But if one or both are plural, then it comes out as “1/12/2021” or “10/8/2021” or “11/16/2020”.

I currently have this code:

df = df.df.strptime(“Date”, “%Y-%m-%d”).strftime(“%m/%d/%Y”)

But the IDE is saying there's a syntax error. And I'm not sure if this is close to correct in terms of making sure the entire column is being changed.

此行将格式“yyyy-mm-dd”更改为“mm/dd/yyyy”

df = df[5:7]+'/'+df[8:10]+'/'+df[0:4]

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