简体   繁体   中英

Pandas: Converting a datetime (%Y-%d-%m %H:%M) to (%Y-%m-%d %H:%M)

I've been up and down and round on this topic with examples, etc, but I cannot seem to get it to work.

I have a pandas dataframe, with a field called Date where I wish to change the format from Year-Day-Month Hours:Minutes to Year-Month-Day Hours:Minutes. The new field will be Date2 . The Date field is has it's type being reported as "Object".

So far I've tried variations on the following:

df['Date2'] = pd.to_datetime(df['Date'], format='%Y-%m-%d %H:%M').dt.strftime('%Y-%d-%m %H:%M')

df['Date2'] = pd.to_datetime(df['Date'], format='%Y-%m-%d %H:%M')

An example date in the Date field is 2020-02-12 04:00
The desired Date2 output would be 2020-12-02 04:00

I did and practice the whole procedure in Google Colab. To get all the source code find my gist

df['Date2']=pd.to_datetime(df["Date"]).dt.strftime("%Y-%m-%d %H:%M")

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