将列类型从对象转换为日期格式 - python

时间:2021-01-25 15:08:19

标签: python excel pandas date object

我连接了两个dataframe,连接前的列类型是datetime,但是连接后的列类型变成了object,当我导出到excel时,它完全变了!

这是两个数据框:

df_last_month:

<头>
项目编号 状态 项目命名 CF VPC CO MA
A 计划中 DH 2021-01-26 2021-03-16 2021-11-16 2023-10-10
B 冻结 DH 2017-12-01 2018-12-18 2019-07-26 2022-02-18
C 计划中 DH 2017-12-01 2018-12-18 2019-07-26 2022-02-18
D 计划中 HH 2017-12-01 2018-12-18 2019-07-26 2022-02-18

df_current_month:

<头>
项目编号 状态 项目命名 CF VPC CO MA
A 计划中 DH 2021-01-10 2021-03-16 2021-09-16 2023-10-10
B 冻结 DH 2017-12-01 2018-12-18 2019-07-26 2022-02-18
E 完成 DH 2017-12-01 2018-12-18 2019-07-26 2022-02-18
F 完成 HH 2017-12-01 2018-12-18 2019-07-26 2022-02-18
H 完成 HH 2017-12-01 2018-12-18 2019-07-26 2022-02-18

我在一些条件下连接了 df1 和 df2,这是代码:

df_last_month = df_last_month.set_index('project number')
df_current_month = df_current_month.set_index('project number')
df3 = pd.concat([df_last_month,df_current_month],sort=False)

df3a = df3.stack().groupby(level=[0,1]).unique().unstack(1).copy()

df3a.loc[~df3a.index.isin(df_last_month.index),'update_project'] = 'new'     

df3a.loc[~df3a.index.isin(df_current_month.index),'update_project'] ='deleted'

idx = df3.stack().groupby(level=[0,1]).nunique() 
df3a.loc[idx.mask(idx<=1).dropna().index.get_level_values(0),
'update_project'='modified'

df3a['update_project'] = df3a['update_project'].fillna('same')

这里是输入:

enter image description here

我想要做的是:在列(CF、CO、MA、VPC)中,我有两种格式:

  • 第一:[2021-01-26 00:00:00]
  • 第二个:[2021-01-26 00:00:00,2021-01-10 00:00:00]
  1. 我想删除时间。

  2. 然后当我导出到 excel 时,我也会有相同的格式,我的意思是 [2021-01-26] 或 [2021-01-26,2021-01-10], 但现在我在 excel 中得到了这个结果:

enter image description here

这是我的代码:

import pandas as pd
import numpy as np
from datetime import datetime, date
# Classify date column by format type
df['format'] = 1
df.loc[df['CF'].astype(str).str.contains(','), 'format'] = 2
df['new_date'] = pd.to_datetime(df['CF'])

# Convert to datetime with two different format settings
df.loc[df.format == 1, 'new_date'] = pd.to_datetime(df.loc[df.format == 1, 'CF'], format = '%Y-%d-%m %H:%M:%S').dt.strftime('%Y-%m-%d')
df.loc[df.format == 2, 'new_date'] = pd.to_datetime(df.loc[df.format == 2, 'CF'], format = '%m/%d/%Y %H:%M:%S,%m/%d/%Y %H:%M:%S').dt.strftime('%Y-%m-%d,%m/%d/%Y')
print(df)

我有这个错误: enter image description here

有什么建议吗?感谢您的帮助

1 个答案:

答案 0 :(得分:1)

在连接两个数据框之前如何将日期时间列转换为字符串。这样你就可以得到你想要的输出。

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

不幸的是,您必须对两个数据帧都执行此操作。