Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

How can I identify date columns and format it to YYYY-MM-DD in Python using pandas?

I am trying to format the dates in Python using Pandas. Basically, I want to identify all the date columns and convert it to YYYY-MM-DD format, overwrite and save it.

Input:

ID NPC_code Date1 Date2 Date3 Date4
1 10001 10-01-2020 11012019 27-Jan-18 27Jan2016
2 10002 11-01-2020 11012020 28-Jan-18 27Jan2017
3 10003 12-01-2020 11012021 29-Jan-18 27Jan2018
4 10004 13-01-2020 11012022 30-Jan-18 27Jan2019
5 10005 14-01-2020 11012023 31-Jan-18 27Jan2020
question from:https://stackoverflow.com/questions/65867773/how-can-i-identify-date-columns-and-format-it-to-yyyy-mm-dd-in-python-using-pand

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If your column is a string, you will need to first use `pd.to_datetime',

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

Then, use .dt datetime accessor with strftime:

df = pd.DataFrame({'Date':pd.date_range('2017-01-01', periods = 60, freq='D')})

df.Date.dt.strftime('%Y-%m-%d').astype(int)

Or use lambda function:

df.Date.apply(lambda x: x.strftime('%Y-%m-%d')).astype(int)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...