【问题标题】:How can I convert this date and time format to datetime?如何将此日期和时间格式转换为日期时间?
【发布时间】:2019-09-03 16:52:31
【问题描述】:

我需要通过读取 .csv 文件将某种日期和时间格式转换为日期时间。值在“Date_start”和“Date_end”列中。该文件有大约 8760 行,但初始日期格式为“dd/mm/yyyy hh:mm”,但在数据的某处它更改为“dd-mm-yyyy hh:mm”。

我几乎尝试了所有方法。 pd.to_datetime 不断要求映射。由于 '-',基于 d.time 和 d.date 的新列会删除后一种格式的日期。

df17_raw.head()
Out[4]: 
      Date_start       Date_end    ...      Total_Ah   Power_kW
0  1/1/2017 0:00  1/1/2017 1:00    ...       392.340  74.897706
1  1/1/2017 1:00  1/1/2017 2:00    ...       393.785  75.173556
2  1/1/2017 2:00  1/1/2017 3:00    ...       388.728  74.208175
3  1/1/2017 3:00  1/1/2017 4:00    ...       386.254  73.735889
4  1/1/2017 4:00  1/1/2017 5:00    ...       393.412  75.102351

[5 rows x 8 columns]

df17_raw.tail()
Out[5]: 
            Date_start          Date_end    ...      Total_Ah   Power_kW
8755  31-12-2017 19:00  31-12-2017 20:00    ...       336.877  64.309819
8756  31-12-2017 20:00  31-12-2017 21:00    ...       327.410  62.502569
8757  31-12-2017 21:00  31-12-2017 22:00    ...       320.638  61.209794
8758  31-12-2017 22:00  31-12-2017 23:00    ...       310.967  59.363600
8759  31-12-2017 23:00     1/1/2018 0:00    ...       306.867  58.580910

[5 rows x 8 columns]

【问题讨论】:

    标签: python csv datetime dataframe


    【解决方案1】:

    您可以将正斜杠 (/) 替换为连字符 (-),然后照常转换为 datetime

    pd.to_datetime(df['Date_end'].str.replace('/', '-'), errors='coerce')
    
    8755   2017-12-31 20:00:00
    8756   2017-12-31 21:00:00
    8757   2017-12-31 22:00:00
    8758   2017-12-31 23:00:00
    8759   2018-01-01 00:00:00
    Name: Date_end, dtype: datetime64[ns]
    

    反之亦然(连字符转斜线)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-03
      • 2016-11-26
      • 2013-03-24
      • 2015-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-09
      相关资源
      最近更新 更多