【问题标题】:Converting dates with multiple formats in a CSV file在 CSV 文件中转换多种格式的日期
【发布时间】:2019-12-06 04:32:17
【问题描述】:

我有一个包含一些标题的 CSV 文件。其中,由于某些未知原因,日期格式从%Y-%m-%d 中途更改为%d/%m/%Y,如下图所示。 这使得尝试将其导出到另一个程序时变得困难,例如MATLAB。我正在尝试在 Python 中解决这个问题,但任何其他解决方案都会很棒。

我已经尝试了多种解决方案,只是通过谷歌搜索。读取CSV、DateTime.strptime等时主要解析为日期格式。我对 Python 很陌生,所以如果我有点不知所措,我很抱歉

我希望标准化所有日期,例如将%d/%m/%Y 更改为另一种格式,同时保持单独的行分开。

我正在考虑遵循here 的方法,但如果它识别出某种格式,则添加一个 if 语句。我将如何分解日期并更改它?

【问题讨论】:

    标签: python pandas csv date-conversion


    【解决方案1】:

    这可能有效,但我懒得对照 CSV 文件的图像检查它。

    import pandas as pd
    
    # Put all the formats into a list
    possible_formats = ['%Y-%m-%d', '%d/%m/%Y']
    
    # Read in the data
    data = pd.read_csv("data_file.csv")
    date_column = "date"
    
    # Parse the dates in each format and stash them in a list
    fixed_dates = [pd.to_datetime(data[date_column], errors='coerce', format=fmt) for fmt in possible_formats]
    
    # Anything we could parse goes back into the CSV
    data[date_column] = pd.NaT
    for fixed in fixed_dates:
        data.loc[~pd.isnull(fixed), date_column] = fixed[~pd.isnull(fixed)]
    
    data.to_csv("new_file.csv")
    

    【讨论】:

    • 是的!这似乎有效。非常感谢,你是救生员。
    猜你喜欢
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    相关资源
    最近更新 更多