猿问

时间数据看似匹配,但与指定的格式不匹配

我在 pandas 中有一个数据框,它有两个日期列:


>>>ID  name    start        end  

0  12  Tik     1/6/2020    None

1  32  Tak     12/31/2019  None

2  45  Tek     9/1/2019   1/30/2020

3  78  Tok     9/1/2019   1/29/2020

我正在尝试将这些日期转换为日期时间,采用 Ymd 格式,例如 12/31/2019 将是 2019-12-31 :


df[['start','end']] =df[['start','end']].apply(pd.to_datetime, format=''%Y-%m-%d'')


但每当我运行这个时,我都会收到错误:


ValueError:时间数据 1/6/2020 与指定的格式不匹配


我尝试将格式指定为给定日期(例如(dmY):


df[['start','end']] =df[['start','end']].apply(pd.to_datetime, format=''%d-%m-%Y'')


>>>ValueError: time data '1/6/2020' does not match format '%d-%m-%Y' (match)

我试图按照这里第一个答案中的建议来打破它:How to Change the datetime format in pandas and to first conver to datetime and then use strftime 但在第一行我收到错误,需要指定格式。


我找不到发生这种情况的任何原因,也许是因为日期和月份没有两位数?


我的最终目标是将这些日期列转换为 %Y-%m-%d 格式


牛魔王的故事
浏览 201回答 1
1回答

呼如林

问题似乎是在格式周围使用了两组引号''...''参数format指定pandas.to_datetime列的当前格式,而不是所需的格式。这些日期的格式是'%m/%d/%Y'import pandas as pd# setup the dataframedf = pd.DataFrame({'ID': [12, 32, 45, 78], 'name': ['Tik', 'Tak', 'Tek', 'Tok'], 'start': ['1/6/2020', '12/31/2019', '9/1/2019', '9/1/2019'], 'end': [None, None, '1/30/2020', '1/29/2020']})# convert to datetimedf[['start','end']] = df[['start','end']].apply(pd.to_datetime, format='%m/%d/%Y')# display(df)   ID name      start        end0  12  Tik 2020-01-06        NaT1  32  Tak 2019-12-31        NaT2  45  Tek 2019-09-01 2020-01-303  78  Tok 2019-09-01 2020-01-29
随时随地看视频慕课网APP

相关分类

Python
我要回答