简体   繁体   中英

convert yyyy-dd-mm to yyyy-mm-dd in python

Please advice how to convert following using python from:

2010-01-04 00:00:00

to:

2010-04-01 00:00:00

I have tried

df.Month = pd.to_datetime(df.Month, format('%Y/%m/%d'))

but didn't work

Thanks in advance

Use .dt.strftime("%Y-%d-%m")

Ex:

import pandas as pd
df = pd.DataFrame({"Date": ["2010-01-04 00:00:00"]})
print( pd.to_datetime(df["Date"]).dt.strftime("%Y-%d-%m") )

Output:

0    2010-04-01
Name: Date, dtype: object

try the following using datetime parser and returning it in a defined format:

from datetime import datetime
old_date_string='2010-01-04 00:00:00'
dt=datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
new_date_string=dt.strftime('%Y-%d-%m %H:%M:%S')

However, when you want to work with the date I would suggest using the datetime object

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