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
174 views
in Technique[技术] by (71.8m points)

excel - Convert the column type from object to date format - python

I have concatenated two dataframes, the column type before concatenation was datetime, but after concatenation the column type changed to object, and when I export to excel it completely changed!

here is the two dataframe:

df_last_month:

project number status Project Naming CF VPC CO MA
A Planned DH 2021-01-26 2021-03-16 2021-11-16 2023-10-10
B frozen DH 2017-12-01 2018-12-18 2019-07-26 2022-02-18
C Planned DH 2017-12-01 2018-12-18 2019-07-26 2022-02-18
D Planned HH 2017-12-01 2018-12-18 2019-07-26 2022-02-18
question from:https://stackoverflow.com/questions/65887358/convert-the-column-type-from-object-to-date-format-python

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

1 Reply

0 votes
by (71.8m points)

How about converting the Datetime columns to string before concatenating the two dataframes. This way you can have the output you wanted.

from pandas.api.types import is_datetime64_any_dtype
    
for col in df_current_month.columns:
        if is_datetime64_any_dtype(df_current_month[col]):
            df_current_month[col] = df_current_month[col].dt.strftime('%Y-%m-%d')

df_current_month['CF'].head()
0    2021-10-01
1    2017-01-12
2    2017-01-12
3    2017-01-12
4    2017-01-12
Name: CF, dtype: object

Unfortunately, you have to do this for both dataframes.


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

...