【问题标题】:Write out Date without time from excel file using Python使用Python从excel文件中写出没有时间的日期
【发布时间】:2018-12-30 17:51:59
【问题描述】:

我正在读取一个 excel 文件并将其合并到一个 csv 文件中。

当我读取 excel 文件时,我有一个日期字段:

0    2018-05-28 00:00:00
1    9999-12-31 00:00:00
2    2018-02-26 00:00:00
3    2018-02-26 00:00:00
4    2018-02-26 00:00:00
Name: Date_started, dtype: object

我检查数据类型

df['Date_started'].dtype
dtype('O')

然后,当我将生成的数据帧写入 csv 时,我得到了这个:

df.to_csv(folderpath + "Date_Started_df.csv",encoding="UTF-8" , index=False, na_rep='',date_format='%d%m%Y')
Date_Started

28/05/2018 00:00
31/12/9999 00:00
26/02/2018 00:00
26/02/2018 00:00
26/02/2018 00:00

我试过了

df.loc[:,'Date_Started'] = df['Date_Started'].astype('str').str[8:10] + "/" + 
df['Date_Started'].astype('str').str[5:7] + "/" + 
df['Date_Started'].astype('str').str[:4] 

这给了我:

0    28/05/2018
1    31/12/9999
2    26/02/2018
3    26/02/2018
4    26/02/2018
Name: Date_started, dtype: object

我想可能是在写出来:

df.to_csv(filename, date_format='%Y%m%d')

但我还有时间!?

【问题讨论】:

    标签: python pandas datetime export-to-csv datetime-format


    【解决方案1】:

    在发送到 CSV 之前,您需要将您的系列转换为 datetime

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

    这将允许 Pandas 使用 to_csv 为适当的列执行 date_format='%d%m%Y'to_csv docs 明确表示:

    日期格式字符串,默认无

    日期时间对象的格式字符串

    【讨论】:

    • 我的问题是我在列表中有假日期(例如 31/12/9999)给出错误“ValueError:给定日期字符串不太可能是日期时间。”
    • 是的,这是一个问题,一个提示是转换为不可能的日期,例如df['Date_Started'] = pd.to_datetime(df['Date_Started'], errors='coerce').fillna(pd.to_datetime('1950-01-01'))。如果您知道 1950 年 1 月 1 日不是有效日期,则可以使用。
    • 会在不可能的日期留下空白吗?因为我实际上需要能够识别它们,因为它们是没有开始日期的记录
    • 我想知道这是否是一个写作问题,因为我设法创建了“字符串”,但是在写入 csv 时添加了时间
    • 要留空,请使用df['Date_Started'] = pd.to_datetime(df['Date_Started'], errors='coerce')。空白将是NaT,也称为“Not a Time”。试试看会发生什么。
    猜你喜欢
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    相关资源
    最近更新 更多